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.
分析:
就是归并排序的merge过程,只不过用链表实现了。
可以递归进行,也可以迭代。
自己的代码又臭又长,但也要记录下来。后面附上比较优秀的代码。
mine:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1)
return l2;
if(!l2)
return l1;
ListNode* current1, *current2;
current1 = l1; current2 = l2;
ListNode* head;
if(l1->val > l2->val) {
head = l2;
current2 = current2->next;
} else {
head = l1;
current1 = current1->next;
}
ListNode* p = head;
while(current1 && current2) {
if(current1->val > current2->val) {
p->next = current2;
current2 = current2->next;
}
else{
p->next = current1;
current1 = current1->next;
}
p = p->next;
}
if(current1) p->next = current1;
if(current2) p->next = current2;
return head;
}
};
简洁代码:—— 增加头结点,省了很多事儿。
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
//为操作方便,添加一个头节点
ListNode node(0), *p = &node;
while(l1 && l2)
{
if(l1->val < l2->val)
{
p->next = l1;
l1 = l1->next;
}
else
{
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if(l1)p->next = l1;
else if(l2)p->next = l2;
return node.next;
}
};