1. 程式人生 > >[LeetCode] Merge Two Sorted Lists

[LeetCode] Merge Two Sorted Lists

合並 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