File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * struct ListNode {
4+ * int val;
5+ * ListNode *next;
6+ * ListNode(int x) : val(x), next(NULL) {}
7+ * };
8+ */
9+ class Solution {
10+ public:
11+ ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
12+
13+ ListNode *result = new ListNode();
14+ ListNode *r= result;
15+ ListNode *first = r; //first用來記錄一開始的位址,否則之後找不回來(因r會變動)
16+
17+ while(l1 && l2){
18+
19+ if(l1->val <= l2->val){
20+ r->next = new ListNode(l1->val);
21+ l1 = l1->next;
22+ }
23+ else {
24+ r->next = new ListNode(l2->val);
25+ l2 = l2->next;
26+ }
27+ r = r->next;
28+ }
29+ if(l1)
30+ r->next = l1;
31+ // 若l1還有,l2沒有,則l1全部加入r
32+ // 為啥可以直接加入?
33+ // 因前面while已比過大小,此時剩下的l1,必定是比較大的數
34+ if(l2)
35+ r->next = l2;
36+
37+ return first->next;
38+
39+ }
40+ };
You can’t perform that action at this time.
0 commit comments