题目:
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.
合并两个有序链表,新链表的元素就是之前的两个链表里面的元素。
程序:
/**
* 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;
}
else if(l2 == NULL)
{
return l1;
}
ListNode *start, *cur;
if(l1->val > l2->val)
{
start = cur = l2;
l2 = l2->next;
}
else
{
start = cur = l1;
l1 = l1->next;
}
while(l1 != NULL && l2 != NULL )
{
if(l1->val < l2->val)
{
cur->next = l1;
cur = cur->next;
l1 = l1->next;
}
else
{
cur->next = l2;
cur = cur->next;
l2 = l2->next;
}
}
if(l1)
{
cur->next = l1;
}
else
{
cur->next = l2;
}
return start;
}
};