leetcode: Merge Two Sorted Lists
2014-12-11 22:22
295 查看
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.
analysis: find a main link and a sub link.
/**
* 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 *pMain, *pSub, *cur, *next;
if (!l1 || !l2) {
return l1 ? l1 : l2;
}
pMain = l1->val < l2->val ? l1 : l2;
pSub = l1->val < l2->val ? l2 : l1;
cur = pMain;
next = cur->next;
while (cur && pSub && next) {
if (cur->val <= pSub->val && next->val >= pSub->val) {
ListNode *tmp = pSub;
pSub = pSub->next;
cur->next = tmp;
tmp->next = next;
} else {
cur = next;
}
next = cur->next;
}
if (pSub) {
cur->next = pSub;
}
return pMain;
}
};
two lists.
analysis: find a main link and a sub link.
/**
* 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 *pMain, *pSub, *cur, *next;
if (!l1 || !l2) {
return l1 ? l1 : l2;
}
pMain = l1->val < l2->val ? l1 : l2;
pSub = l1->val < l2->val ? l2 : l1;
cur = pMain;
next = cur->next;
while (cur && pSub && next) {
if (cur->val <= pSub->val && next->val >= pSub->val) {
ListNode *tmp = pSub;
pSub = pSub->next;
cur->next = tmp;
tmp->next = next;
} else {
cur = next;
}
next = cur->next;
}
if (pSub) {
cur->next = pSub;
}
return pMain;
}
};
相关文章推荐
- leetcode-21Merge Two Sorted Lists
- Leetcode 21 Merge Two Sorted Lists 将两个已排序的链表合并起来
- Leetcode|Merge Two Sorted Lists
- LeetCodet题解--21. Merge Two Sorted Lists(合并两个排序好的链表)
- LeetCode:Merge Two Sorted Lists
- 21 - Merge Two Sorted Lists - LeetCode
- leetcode第21题——*Merge Two Sorted Lists
- leetcode 21 Merge Two Sorted Lists
- leetcode 21: Merge Two Sorted Lists
- LeetCode之Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- leetcode(21). Merge Two Sorted Lists
- Leetcode:Merge Two Sorted Lists(Importance!)
- [LeetCode] Merge Two Sorted Lists
- leetcode笔记:Merge Two Sorted Lists
- Leetcode (2) Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- LeetCode 21:Merge Two Sorted Lists
- LeetCode[链表] - #21 Merge Two Sorted Lists