原創博客,轉載請注明出處!
1.題目
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成后的鏈表(單調不減)。
2.思路(遞歸)
# 魯棒性:
如果鏈表1是空鏈表,則直接輸出鏈表2。
如果鏈表2是空鏈表,則直接輸出鏈表1。
# 遞歸思路:
定義三個指針,指向鏈表1頭結點的指針p1,指向鏈表2頭結點的指針p2,指向合並后鏈表頭節點的指針head。比較p1和p2的值,如果p1<p2,那么head指向p1,p1指向p1的下一個節點;如果p1>p2,那么head指向p2,p2指向p2的下一個節點。依次類推……
3.代碼
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 };*/ 9 class Solution { 10 public: 11 ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 12 { 13 // 魯棒性(邊界檢查) 14 if(pHead1==nullptr) 15 return pHead2; 16 17 if(pHead2==nullptr) 18 return pHead1; 19 20 // 遞歸合並 21 ListNode* head = nullptr; 22 if(pHead1->val < pHead2->val) 23 { 24 head = pHead1; 25 head->next = Merge(pHead1->next,pHead2); 26 } 27 else 28 { 29 head = pHead2; 30 head->next = Merge(pHead1,pHead2->next); 31 } 32 33 return head; 34 35 } 36 };
4.測試用例
# 邊界測試
- 鏈表1是空指針
- 鏈表2是空指針
- 鏈表1和鏈表2是空指針
# 功能測試
- 兩個鏈表有多個節點,節點的值互不相同
- 兩個鏈表有多個節點,存在值相等的多個節點