1. 程式人生 > >[劍指offer] 16. 合併兩個排序的連結串列

[劍指offer] 16. 合併兩個排序的連結串列

題目描述

輸入兩個單調遞增的連結串列,輸出兩個連結串列合成後的連結串列,當然我們需要合成後的連結串列滿足單調不減規則。
解法一: 非遞迴解
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;
    }
  }
};