LeetCode.21 - Merge Two Sorted Lists
阿新 • • 發佈:2018-03-16
算法 tput out oge 其中 png 就會 std info
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:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
題意就是合並兩個排序鏈表。
我的算法思路:維護其中一個鏈表,另一個鏈表從頭往後不斷縮減,並將每次出隊的節點插入到第一個鏈表中。因此時間復雜度為O(n),空間復雜度為O(1)。
然而LeetCode給的鏈表接口是head->next,所以我的代碼只能合並從第二個節點開始的剩余部分。
傳入參數為頭節點(head)的方案:
#include <iostream> struct ListNode { int val; ListNode *next; //ListNode(int x) : val(x), next(NULL) {} }; ListNode* Create_LinkList_1(int Length) { ListNode*L1, *rear, *memory; L1 = new ListNode; rear = L1; for(int i = 1; i <= Length; i++) { memory = new ListNode; std::cout << "L1:"; std::cin >> memory->val; rear->next = memory; rear = memory; } rear->next = nullptr; return L1; } ListNode* Create_LinkList_2(int Length) { ListNode*L2, *rear, *memory; L2 = new ListNode; rear = L2; for(int i = 1; i <= Length; i++) { memory = new ListNode; std::cout << "L2:"; std::cin >> memory->val; rear->next = memory; rear = memory; } rear->next = nullptr; return L2; } class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!(l1 && l2)) return nullptr; else if(l1 && !l2) return l1; else if(!l1 && l2) return l2; else { // 2->4->6 1->3->5 ListNode*head = l1; ListNode*p1 = l1->next; ListNode*p2 = l2->next; ListNode*q1; while(p1 && p2) { if(p1->val >= p2->val) { ListNode*node = p2; p2 = p2->next; node->next = p1; if(p1 == head->next) head->next = node; else q1->next = node; p1 = node; p1 = p1->next; } q1 = p1; p1 = p1->next; } if (p2) q1->next = p2; return head; } } }; int main() { Solution solve; ListNode* L1, *L2; L1 = Create_LinkList_1(3); L2 = Create_LinkList_2(3); ListNode*head = solve.mergeTwoLists(L1, L2)->next; while(head) { std::cout << head->val << ‘ ‘; head = head->next; } return 0; }
傳入參數是head->next的方案:
/** * 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 && l2)) return NULL; else if(l1 && !l2) return l1; else if(!l1 && l2) return l2; else { ListNode*head = l1; ListNode*q1 = l1; while(l1 && l2) { if(l1->val >= l2->val) { ListNode*node = l2; l2 = l2->next; if (head == l1) { node->next = l1->next; l1->next = node; } else { node->next = l1; q1->next = node; l1 = node; } l1 = l1->next; } q1 = l1; l1 = l1->next; } if (l2) q1->next = l2; return head; } } };
但沒有過:
目前我猜測是因為LeedCode的特殊數據,鏈表l1只有1個節點(還有一個頭節點,但傳入的是l1=head->next),且不為空,但沒有給成員val賦值,這樣的話,我的算法就會被卡住了。
LeetCode.21 - Merge Two Sorted Lists