题目:
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.
思路:
Easy级别的题目,没有特别的技巧。还是那句老话,在链表处理中如果能加一个虚拟头结点,可以避免处理节点为空等特殊情况,让代码看起来更加的简洁和优雅。此外,在while循环中,将循环条件改为(l1 && l2),可以在某一链表到达末尾的时候提前返回,从而总体上减少运行时间。
代码:
/**
* 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 pre_head(0), *p = &pre_head; // virtual head 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
p->next = l2;
return pre_head.next;
}
};