题目描述
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
提示:
两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1
和 l2
均按 非递减顺序 排列
题解
创建新链表依次往里放
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
// Define an alias for struct ListNode as ListNode
typedef struct ListNode ListNode;
// Function to merge two sorted linked lists
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
// If either list is empty, return the other list
if (list1 == NULL) {
return list2;
}
if (list2 == NULL) {
return list1;
}
// Define pointers l1 and l2 to point to the head nodes of list1 and list2
ListNode* l1, *l2;
ListNode* newhead, *newtail;
// Create a dummy node for the new merged list
newhead = newtail = (ListNode*)malloc(sizeof(ListNode));
l1 = list1, l2 = list2;
// Merge the two lists in sorted order
while (l1 && l2) {
if (l1->val <= l2->val) {
newtail->next = l1;
newtail = newtail->next;
l1 = l1->next;
} else {
newtail->next = l2;
newtail = newtail->next;
l2 = l2->next;
}
}
// Append the remaining elements from list1 or list2
if (l1) {
newtail->next = l1;
}
if (l2) {
newtail->next = l2;
}
// The first node of the new list is a dummy node, so return the next of the dummy node
return newhead->next;
}
作者:凪
链接:https://leetcode.cn/problems/merge-two-sorted-lists/solutions/2619565/chuang-jian-xin-lian-biao-yi-ci-wang-li-zrhyf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。