Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
这道题的解法跟上一篇博客中的揭发雷同,这个相当于重排一下单链表的指针,使两个有序的单链表合并以后还是有序的。C++代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *head = NULL, *curNode = NULL;
if(!l1 && !l2)
return NULL;
else if(!l1)
return l2;
else if(!l2)
return l1;
while(l1 && l2)
{
if(l1->val > l2->val)
{
if(!head){
head = l2;
curNode = head;
}
else
{
curNode->next = l2;
curNode = curNode->next;
}
l2 = l2->next;
}
else
{
if(!head){
head = l1;
curNode = head;
}
else
{
curNode->next = l1;
curNode = curNode->next;
}
l1 = l1->next;
}
}
ListNode *tempNode = l1 ? l1:l2;
while(tempNode)
{
curNode->next = tempNode;
tempNode = tempNode->next;
curNode = curNode->next;
}
return head;
}
};
- 测试代码如下:
int main(int argc, const char * argv[])
{
vector<int> numbers = vector<int>{-1, 0, 1, 2, -1, -4};
ListNode *head = new ListNode(1);
ListNode *mid = new ListNode(5);
mid->next = NULL;
head->next = mid;
ListNode *last = new ListNode(8);
last->next = NULL;
mid->next = last;
ListNode *head2 = new ListNode(4);
ListNode *mid2 = new ListNode(6);
mid2->next = NULL;
head2->next = mid2;
ListNode *last2 = new ListNode(9);
last2->next = NULL;
mid2->next = last2;
cout<<"Show time!"<<endl;
ListNode *ret = mergeTwoLists(head, head2);
while(ret)
{
cout<<ret->val;
ret = ret->next;
}
cout<<endl;
return 0;
}