美文网首页
剑指Offer - 16 - 合并两个排序的链表

剑指Offer - 16 - 合并两个排序的链表

作者: vouv | 来源:发表于2019-06-05 14:45 被阅读0次

题目描述

合并两个排序的链表

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路

若链表1的头结点的值小于链表2的头结点的值,则链表1的头结点是合并后链表的头结点。在剩余的结点中,链表2的头结点的值小于链表1的头结点的值,因此链表2的头结点是剩余结点的头结点,把这个结点和之前已经合并好的链表的尾结点链接起来。

Code

  • Python
class Solution:
    # 返回合并后列表
    def Merge(self, pHead1, pHead2):
        # write code here
        if pHead1 is None:
            return pHead2
        if pHead2 is None:
            return pHead1
        if pHead1.val < pHead2.val:
            pHead1.next = self.Merge(pHead1.next,pHead2)
            return pHead1
        else:
            pHead2.next = self.Merge(pHead1,pHead2.next)
            return pHead2
  • JavaScript
/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function Merge(pHead1, 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 - 合并两个排序的链表

      本文链接:https://www.haomeiwen.com/subject/sxmgnqtx.html