21. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
解法1:
定义两个指针ps1和ps2,分别指向两个链表首元素进行比较。小的放入新链表。如果相等放哪个都行。
放入新链表的指针此时向后移动,继续比较。tail向后移动。
如果其中一个链表已经到达尽头,由于是有序数组。说明第二个链表剩下的元素都比第一个链表大,直接将未遍历结束链表的剩下的元素逐个放入新链表。
代码示例:
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL && l2 == NULL)
return NULL;
//开辟一个新节点存储新链表。
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
//保存链表尾部指针
struct ListNode* tail = head;
//有一个链表遍历到达尾部就结束循环。
while (l1 && l2)
{
if (l1->val < l2->val)
{
tail->next = l1;
l1 = l1->next;
tail = tail->next;
}
else
{
tail->next = l2;
l2 = l2->next;
tail = tail->next;
}
}
//l1如果未遍历完直接将剩下元素添加新链表。
while (l1)
{
tail->next = l1;
l1 = l1->next;
tail = tail->next;
}
1. List item
//同理。
while (l2)
{
tail->next = l2;
l2 = l2->next;
tail = tail->next;
}
//返回新链表头部。
return head->next;
}