Leetcode21. Merge Two Sorted Lists
2017-12-21 22:55
471 查看
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.
Example:
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
这题断断续续刷了好久,好讨厌coding被人打断,忧桑...
其实还挺简单的一道链表合并。
#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) { ListNode* head = NULL; if (l1 == NULL&&l2 == NULL) return 0; else if (l1 == NULL&&l2 != NULL) return l1; else if (l1 != NULL&&l2 == NULL) return l2; ListNode* p = l1; ListNode* q = l2; ListNode* tail = NULL; if (p->val <= q->val) { head = p; p = p->next; } else { head = q; q = q->next; } tail = head; while (p != NULL&&q != NULL) { if (p->val <= q->val) { tail->next = p; p = p->next; } else { tail->next = q; q = q->next; } tail = tail->next; } if (p != NULL) tail->next = p; else tail->next = q; return head; } }; int main() { ListNode* a = new ListNode(1); ListNode* b = new ListNode(2); ListNode* c = new ListNode(3); ListNode* d = new ListNode(1); ListNode* e = new ListNode(3); ListNode* f = new ListNode(4); a = NULL; d = NULL; /*a->next = b; b->next = c; c->next = NULL; d->next = e; e->next = f; f->next = NULL;*/ Solution s; ListNode* head; head = s.mergeTwoLists(a, d); while (head != NULL) { cout << head->val; head = head->next; } }
相关文章推荐
- 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--21. Merge Two Sorted Lists
- Leetcode: 21. Merge Two Sorted Lists
- 个人记录-LeetCode 21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- leetcode 21. Merge Two Sorted Lists
- [LeetCode-Java]21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- LeetCode笔记:21. Merge Two Sorted Lists
- leetcode --21. Merge Two Sorted Lists
- 【leetcode】21. Merge Two Sorted Lists
- Leetcode 21. Merge Two Sorted Lists
- LeetCode-----21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- Leetcode-21. Merge Two Sorted Lists
- leetcode 21. Merge Two Sorted Lists
- Leetcode 21. Merge Two Sorted Lists