标签:item div scribe offer 规则 非递归 ext merge public
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; } } };
标签:item div scribe offer 规则 非递归 ext merge public
原文地址:https://www.cnblogs.com/ruoh3kou/p/10052215.html