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的方式,比较方便.