[劍指offer] 16. 合並兩個排序的鏈表
阿新 • • 發佈:2018-12-02
劍指offer style spa class tle offer bottom 題目 合並兩個排序的鏈表
解法一: 非遞歸解
題目描述
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。解法一: 非遞歸解
class Solution { public: ListNode *Merge(ListNode *pHead1, ListNode *pHead2) { if (pHead1 == NULL) return pHead2; if (pHead2 == NULL) return pHead1; ListNode *a = pHead1; ListNode *b = pHead2; ListNode*res = NULL; ListNode *cur = NULL; while (a != NULL && b != NULL) { if (a->val < b->val) { if (res == NULL) { res = cur = a; } else { cur->next = a; cur = cur->next; } a= a->next; } else { if (res == NULL) { res = cur = b; } else { cur->next = b; cur = cur->next; } b = b->next; } } if (a == NULL) cur->next = b; else cur->next = a; return res; } };
解法二:
遞歸解
class Solution { public: ListNode *Merge(ListNode *pHead1, ListNode *pHead2) { if (pHead1 == NULL) return pHead2; if (pHead2 == NULL) return pHead1; if (pHead1->val < pHead2->val) { pHead1->next = Merge(pHead1->next, pHead2); return pHead1; } else { pHead2->next = Merge(pHead1, pHead2->next); return pHead2; } } };
[劍指offer] 16. 合並兩個排序的鏈表