LeetCode OJ 之 Merge Two Sorted Lists(合併兩個有序的連結串列)
阿新 • • 發佈:2019-01-01
題目:
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.
合併兩個排序的連結串列,並返回一個新的連結串列。新連結串列應由兩個連結串列拼接而成。
/** * 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) { //l1為空,則返回l2,l2為空,則返回l1 if (l1 == NULL) return l2; if (l2 == NULL) return l1; //q結點記錄連結串列的起始結點 ListNode q(-1); ListNode *p=&q; //迴圈判斷l1和l2大小,小的連結到p後,迴圈結束條件是l1和l2之間有一個先遍歷完 while(l1 != NULL && l2 != NULL) { if(l1->val <= l2->val) { p->next = l1; p = p->next; l1 = l1->next; } else { p->next = l2; p = p->next; l2 = l2->next; } } //如果l2先遍歷完,把l1接到p後即可 if(l1) { p->next = l1; } if(l2) { p->next = l2; } //返回連線後連結串列的首結點,不是q,q不屬於l1和l2,而是q->next return q.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 == NULL) return l2; if(l2 == NULL) return l1; ListNode *p = NULL; if(l1->val < l2->val) { p = l1; p->next = mergeTwoLists(l1->next , l2); } else { p = l2; p->next = mergeTwoLists(l1 , l2->next); } return p; } };