1. 程式人生 > 實用技巧 >AtCoder agc013_d - Piling Up

AtCoder agc013_d - Piling Up

21. 合併兩個有序連結串列

難度簡單1172將兩個升序連結串列合併為一個新的 升序 連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。 示例: 輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4 程式碼:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 
*/ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode *mirror,*pre; mirror = new ListNode; pre = mirror; while(l1&&l2) { if(l1->val<l2->val) { pre->next = l1;//1->1
l1 = l1->next;//p1 = 2 } else { pre->next = l2;//0->1 l2 = l2->next;//p2 = 3 } pre = pre->next;//pre = 1 } pre->next = l1 == NULL ? l2 : l1; return mirror->next;
delete(mirror); } };