LeetCode OJ--Merge Two Sorted Lists
2014-01-18 10:26
330 查看
http://oj.leetcode.com/problems/merge-two-sorted-lists/
有序链表的归并排序
有序链表的归并排序
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { // default as asend sorted,merge sort ListNode *ans = NULL,*ansEnd = NULL,*n1 = l1,*n2 = l2; bool firstone = 1; while(n1&&n2) { while(n1->val <= n2 ->val) { if(firstone == 1) { ans = ansEnd = n1; //ansEnd = ans->next; firstone = 0; n1 = n1->next; } else { ansEnd->next = n1; ansEnd = n1; n1 = n1->next; } if(n1 == NULL) break; } if(n1 == NULL) break; while(n1->val > n2->val) { if(firstone == 1) { ans = ansEnd = n2; firstone = 0; n2 = n2->next; } else { ansEnd->next = n2; ansEnd = n2; n2 = n2->next; } if(n2 == NULL) break; } } if(n1==NULL && n2!= NULL) { if(firstone ==1) { ans = n2; return ans; } ansEnd->next = n2; } else if(n2 == NULL && n1 != NULL) { if(firstone == 1) { ans = n1; return ans; } ansEnd->next = n1; } return ans; } }; int main() { ListNode *n1 = new ListNode(1); ListNode *n2 = new ListNode(3); ListNode *n3 = new ListNode(5); n1->next = n2; Solution myS; ListNode *ans = myS.mergeTwoLists(NULL,NULL); return 0; }
相关文章推荐
- LeetCode OJ 之 Merge Two Sorted Lists(合并两个有序的链表)
- LeetCode OJ - Merge Sorted Array & Merge Two Sorted Lists
- LeetCode OJ - Merge Two Sorted Lists
- 【LeetCode OJ】Merge Two Sorted Lists
- 【LeetCode OJ】Merge Two Sorted Lists
- LeetCode OJ:Merge Two Sorted Lists
- LeetCode OJ:Merge Two Sorted Lists(合并两个链表)
- LeetCode OJ 之Merge TwoSorted Lists 解题报告
- [LeetCode OJ]Merge Two Sorted Lists
- LeetCode OJ——Merge Two Sorted Lists
- 0021_Merge Two Sorted Lists
- leetcode -- Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- LeetCode - 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- leetcode 21 -- Merge Two Sorted Lists
- leetcode 21 Merge Two Sorted Lists
- leetcode[21]:Merge Two Sorted Lists
- Leet Code OJ 21. Merge Two Sorted Lists [Difficulty: Easy]
- LeetCode (6). Merge Two Sorted Lists