一.題目
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.
二.解題技巧
三.實現代碼
#include <iostream>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (!l1)
{
return l2;
}
if (!l2)
{
return l1;
}
ListNode Head(0);
ListNode *Pre = &Head;
while(l1 && l2)
{
if (l1->val < l2->val)
{
Pre->next = l1;
l1 = l1->next;
Pre = Pre->next;
}
else
{
Pre->next = l2;
l2 = l2->next;
Pre = Pre->next;
}
}
while (l1)
{
Pre->next = l1;
l1 = l1->next;
Pre = Pre->next;
}
while(l2)
{
Pre->next = l2;
l2 = l2->next;
Pre = Pre->next;
}
return Head.next;
}
};