题目:
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.
分析:将两个排好序的list弄一个排好序的list。基本思想,就是在不新建空间的情况下,改变指针的方向。
代码:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head;
ListNode* l = head;
head->next = l1;
while(l1 != NULL && l2 != NULL)
{
if(l1->val > l2 -> val)
{
ListNode* next = l2->next;
l2->next = l->next;
l->next = l2;
l2 = next;
}
else
{
l1 = l1->next;
}
l = l -> next;
}
if(l2 != NULL)
{
l->next = l2;
}
return head->next;
}
2014广东华为实习生面试的时候,被问过。当时忘记怎么弄的了。其实,在这之前,学习数据结构的时候,应该是做过这道题的。这就说明,平时代码不会,看了别人思路,自己不写,是依旧不怎么会的啊。