用尾插的思路实现 “合并两个有序链表”
一、题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = [] 输出:[]
示例 3:
输入:l1 = [], l2 = [0] 输出:[0]
提示:
- 两个链表的节点数目范围是
[0, 50]
-100 <= Node.val <= 100
l1
和l2
均按 非递减顺序 排列
二、思路
1.类比数组的合并,遍历两个链表所有节点。
2.建立tail指针与newhead指针,完成节点“插入”
三、代码
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {//链表本身就可能为空!!! 一定不可省略!!!if(list1 == NULL)return list2;else if(list2 == NULL)return list1;struct ListNode* cur1 = list1;struct ListNode* cur2 = list2;struct ListNode* newhead = NULL; struct ListNode* tail = NULL; while(cur1 && cur2){ if(cur1->val <= cur2->val){if(newhead == NULL){newhead = tail = cur1;}else{tail->next = cur1;tail = tail->next;}cur1 = cur1->next;}else{if(newhead == NULL){newhead = tail = cur2;}else{tail->next = cur2;tail = tail->next;}cur2 = cur2->next;}}//跳出循环,意味着某个链表结束if(cur2) //cur1 为空,cur2不能为空!tail->next = cur2;else if(cur1)tail->next = cur1;return newhead;
}
四、注意点
1.跳出循环,一定意味着某个链表结束
2.if(cur2) //如果cur2不会空
要去判断谁不为空,而不是谁为空!
3.tail指针是尾插新链表的尾节点,在逻辑上,tail指针落后于 或者 齐平于cur指针!
五、注:
若想更深入了解尾插的应用及内涵,见此链接
用尾插的思想实现移除链表中的元素-CSDN博客