c - 如何在C中合并两个链表

标签 c linked-list singly-linked-list

我在 C 中得到两个排序的链表,我试图将它们合并在一起,以便它们按排序顺序排列。谁能告诉我为什么我的代码不起作用。

struct ListNode {
    int val;
    struct ListNode *next;
};

struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) {

    struct ListNode *node;

    node = NULL;

    struct ListNode *n = (struct ListNode *)malloc(sizeof(struct ListNode));

    node = n;

    while (l1 != NULL && l2 != NULL) {
        if ((*l1).val < (*l2).val) {
            (*n).val = (*l1).val;
            l1 = (*l1).next;
        } else {
            (*n).val = (*l2).val;
            l2 = (*l2).next;
        }
        (*n).next = (struct ListNode *)malloc(sizeof(struct ListNode));
        n = (*n).next;
    }
    if (l1 != NULL) {
        n = l1;
    }
    if (l2 != NULL) {
        n = l2;
    }
    return node;
}

最佳答案

  • 首先,决定是要合并原始列表,还是要返回列表的副本(但具有相同的值)
  • 如果您想要一个副本,对于您传递的每个输入节点,应该有恰好一个 malloc()。 (您可以验证在合并循环中,l1l2 是高级的,并且(可能)分配了一个节点)

#include <stdio.h>

struct node {
        struct node *next;
        int val;
        };

#if WANT_CLONE
#include <stdlib.h>
struct node *clone(struct node *p)
{
struct node *q;
if (!p) return NULL;
q = malloc (sizeof *q);
*q = *p;
return q;
}

#define CLONE(x) clone(x)
#else
#define CLONE(x) (x)
#endif

struct node *merge(struct node *l1, struct node *l2)
{
struct node dummy = {NULL,0}, *here;

for(here = &dummy; l1 || l2; here = here->next) {
        if (!l2 || l1 && l1->val <= l2->val) {
                here->next= CLONE(l1); l1 = l1->next;
                }
        else    if(!l1 || l2) {
                here->next= CLONE(l2); l2 = l2->next;
                }
        }

return dummy.next;
}

        /* Some test data */
struct node evens[] = {
{evens+1, 0}, {evens+2, 2}, {evens+3, 4}, {evens+4, 6}, {NULL, 8}, };

struct node odds[] = {
{odds+1, 1}, {odds+2, 3}, {odds+3, 5}, {odds+4, 7}, {odds+5, 9}, {NULL, 11}, };

void print(struct node *p)
{
for( ; p; p = p->next) {
        printf(" %d", p->val);
        }
printf("\n");
}

int main(void)
{
struct node *both;

printf("odds:"); print(odds);
printf("evens:"); print(evens);
both = merge(odds, evens);
printf("both:"); print(both);

printf("odds:"); print(odds);
printf("evens:"); print(evens);

return 0;
}

关于c - 如何在C中合并两个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57975710/

相关文章:

c - 在 TIC TAC TOE 游戏中生成下一步 Action 的最快方法

c - 在 gcc 中激活 int - float 操作的警告

c - 用 C 打印数字模式

c - 删除双向链表中的链接

c++ - 在分类袋中添加C++

python - 在 Python 的 C/C++ 扩展中,返回的 PyObject* 应该具有多少引用计数?

这段代码可以优化吗?

java - 如何评估通过链表或数组列表实现的二叉树的性能?

c++ - 我试图按升序将两个链表合并为 1 个链表

java - 将节点插入链表中间,不小心也插入了空节点