您的位置:首页 > 其它

Leetcode 线性表 Merge Two Sorted Lists

2014-05-14 17:55 316 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Merge Two Sorted Lists

 Total Accepted: 14176 Total
Submissions: 44011

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.

题意:将两个已排好序的链接合并成一个有序链表

思路:归并排序的合并步骤,用两个指针分别指向两个链表,

每次新链表的指针指向值小的那个节点,并分别前进该节点的链表指针和新链表的指针

遍历的次数为短链表的长度

遍历后把新链表的指针指向长链表的剩余部分

小技巧:刚开始的时候,cur指针为NULL,cur->next未定义,可以使用一个dummy变量,让l3和cur指向该变量

返回值的时候,再把l3前移一步就可以了。

复杂度:时间O(m+n), 空间O(1)

/**
* 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){
if(!l1) return l2;
if(!l2) return l1;
ListNode *l3, *cur;
ListNode dummy(-1);
l3 = cur = &dummy;
while(l1&&l2){
if(l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
}else{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if(l1) cur->next = l1;
else cur->next = l2;
return l3->next;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: