LeetCode 21 Merge Two Sorted Lists 链表合并
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Solution
先新建一个头节点:
点击查看代码
ListNode newhead(0);
ListNode* p = &newhead;
然后利用双指针即可:
点击查看代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
// create a new headnode
ListNode newhead(0);
ListNode* p = &newhead;
if(!list1 && !list2) return nullptr;
else if(!list1) return list2;
else if(!list2) return list1;
else{
while(list1||list2){
if(!list1){
while(list2){
p->next = list2;
p = p->next;
list2 = list2->next;
}
break;
}
if(!list2){
while(list1){
p->next = list1;
p = p->next;
list1 = list1->next;
}
break;
}
if(list1->val <= list2->val){
p->next = list1;
p = p->next;
list1 = list1->next;
}
else {
p->next = list2;
p = p->next;
list2 = list2->next;
}
}
}
return newhead.next;
}
};