[LeetCode] Merge Two Sorted Lists
阿新 • • 發佈:2017-08-23
合並 linked new ace oge tco div nullptr etc
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.
此題為兩個鏈表的合並,合並後的表頭節點不一定,故應聯想到使用dummy節點。鏈表節點的插入主要涉及節點next
指針值的改變,兩個鏈表的合並操作則涉及到兩個節點的next
值變化,若每次合並一個節點都要改變兩個節點next
的值且要對NULL
指針做異常處理,勢必會異常麻煩。嗯,第一次做這個題時我就是這麽想的… 下面看看相對較好的思路。
首先dummy
節點還是必須要用到,除了dummy
節點外還引入一個lastNode
節點充當下一次合並時的頭節點。在l1
或者l2
的某一個節點為空指針NULL
時,退出while
循環,並將非空鏈表的頭部鏈接到lastNode->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) { ListNode* dummy = new ListNode(0); ListNode* cur = dummy; while (l1 != nullptr && l2 != nullptr) { if (l1->val < l2->val) { cur->next = l1; l1 = l1->next; }else { cur->next = l2; l2 = l2->next; } cur = cur->next; } cur->next = (l1 != nullptr) ? l1 : l2; return dummy->next; } }; // 12 ms
[LeetCode] Merge Two Sorted Lists