Leetcode 线性表 Merge Two Sorted Lists
2014-05-14 17:55
316 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
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)
Merge Two Sorted Lists
Total Accepted: 14176 TotalSubmissions: 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; } };
相关文章推荐
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)
- leetcode Merge Two Sorted Lists
- leetcode Merge Two Sorted Lists
- [Leetcode]Merge Two Sorted Lists
- LeetCode::Merge Two Sorted Lists
- leetcode - Merge Two Sorted Lists
- leetcode笔记:Merge Two Sorted Lists
- 【LeetCode从零单排】No21.MergeTwoSortedLists
- leetcode之Merge Two Sorted Lists
- LeetCode No.21 MergeTwoSortedLists
- [leetcode]Merge Two Sorted Lists @ Python
- leetcode 21 Merge Two Sorted Lists C++
- [LeetCode] Merge Two Sorted Lists
- Leetcode-21:Merge Two Sorted Lists
- leetcode解题方案--021--Merge Two Sorted Lists
- [LeetCode]题解(python):021-Merge Two Sorted Lists
- LeetCode: Merge Two Sorted Lists
- LeetCode|Merge Two Sorted Lists/Merge Sorted Array
- Leetcode Merge Two Sorted Lists
- LeetCode--------Merge Two Sorted Lists