合并两个有序数列。属于基础的数据结构问题,核心在于对链表的操作。
代码如下:
/**
* 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* head1 = NULL;
ListNode* head2 = NULL;
ListNode* tmp = NULL;
if(l1 == NULL)
{
return l2;
}
else if(l2 == NULL)
{
return l1;
}
else if(l1->val > l2->val)
{
tmp = l2;
head1 = l1;
head2 = l2->next;
}
else
{
tmp = l1;
head1 = l1->next;
head2 = l2;
}
ListNode* node = tmp;
while(true)
{
if(head1 == NULL)
{
node->next = head2;
break;
}
if(head2 == NULL)
{
node->next = head1;
break;
}
if(head1->val > head2->val)
{
node->next = head2;
head2 = head2->next;
}
else
{
node->next = head1;
head1 = head1->next;
}
node = node->next;
}
return tmp;
}
};