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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
這道題目主要考察的是對鏈表的理解,如何拆,如何拼接,以及如何新建.
我對於鏈表的思路一直是分三步走,head,tail,temp.
/**
* 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) {
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode *merged = new ListNode(0);
/////select the small one
if(l1->val < l2->val)
{
merged->val = l1->val;
l1 = l1->next;
}
else
{
merged->val = l2->val;
l2 = l2->next;
}
ListNode *tail,*temp ;
temp=tail= merged;
while ((l1)!=NULL && (l2)!=NULL)
{
if(l1->val < l2->val)
{
temp = l1;
tail->next= temp;
l1 = l1->next;
tail = temp;
}
else
{
temp= l2;
tail->next= temp;
l2 = l2->next;
tail = temp;
}
}
if(l1 == NULL)
{
tail->next = l2;
}
if(l2 == NULL)
{
tail->next = l1;
}
return merged;
}
};
Note: 在鏈表元素的結構體中創建一個構造函數,在新建結構對象的時候,直接採用new的方式,比較方便.