初阶数据结构习题【7】(3顺序表和链表)——21.合并两个有序链表
- 电脑硬件
- 2025-09-11 02:45:01

1. 题目描述
力扣在线OJ——21合并两个有序链表 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例1 输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例 2: 输入:l1 = [], l2 = [] 输出:[]
示例 3: 输入:l1 = [], l2 = [0] 输出:[0]
2. 思路合并两个链表和合并两个数组的最简单思路都一样的,都是从两个表中比较元素,谁小就放到新的表中;
定义newhead = NULL,tail = NULL; newhead 是新链表的头,tail是新链表的尾部;比较cur1->val 和 cur2->val ,谁小就谁插入newhead的尾巴tail->next中;tips1:第一次插入的时候,头插的逻辑要单独处理,因为tail == NULL,无法使用tail->next;tips2:cur1和cur2比较到尾时候,谁先结束到尾,还没到尾的,直接把剩下的链表插入到newhead链表中,即tail->next,因为是链表,所以直接链接过去就好了,不用一个一个搬。 3.代码实现1 struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) { if (list1 == NULL) { return list2; } if (list2 == NULL) { return list1; } struct ListNode* cur1 = list1; struct ListNode* cur2 = list2; struct ListNode* head = NULL; struct ListNode* tail = NULL; while (cur1&&cur2) {//有一个结束就结束了,我们写的是继续的条件,两个都不为空才是我们的继续条件 if (cur1->val < cur2->val) { if (head == NULL) { head = tail = cur1; } else { tail->next= cur1; tail = tail->next; } cur1 = cur1->next; } else { if (head == NULL) { head = tail = cur2;//刚开始head==NULL 的时候,先进行赋值, } else { tail->next= cur2; tail = tail->next; } cur2 = cur2->next; } } if(cur1) { tail->next = cur1; } if(cur2) { tail->next = cur2; } return head; } 4.代码实现2带哨兵的链表实现
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) { struct ListNode *cur1 = list1, *cur2 = list2; struct ListNode *guard = NULL, *tail = NULL; guard = tail = (struct ListNode*)malloc(sizeof(struct ListNode)); tail->next = NULL; while (cur1 && cur2) { if (cur1->val < cur2->val) { tail->next = cur1; tail = tail->next; cur1 = cur1->next; } else { tail->next = cur2; tail = tail->next; cur2 = cur2->next; } } if (cur1) { tail->next = cur1; } if (cur2) { tail->next = cur2; } struct ListNode* head = guard->next; free(guard); guard = NULL; return head; }初阶数据结构习题【7】(3顺序表和链表)——21.合并两个有序链表由讯客互联电脑硬件栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“初阶数据结构习题【7】(3顺序表和链表)——21.合并两个有序链表”