码迷,mamicode.com
首页 > 编程语言 > 详细

[剑指offer] 16. 合并两个排序的链表

时间:2018-12-02 12:08:13      阅读:174      评论:0      收藏:0      [点我收藏+]

标签: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;
    }
  }
};

 

[剑指offer] 16. 合并两个排序的链表

标签:item   div   scribe   offer   规则   非递归   ext   merge   public   

原文地址:https://www.cnblogs.com/ruoh3kou/p/10052215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!