zoukankan      html  css  js  c++  java
  • 剑指offer16-合并两个排序的链表

    题目描述

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

    示例

    输入      {1,3,5},{2,4,6}

    返回值  {1,2,3,4,5,6}

    知识点回顾

    排序链表合并

    代码

    #递归法
    #
    -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): # write code here if pHead1==None: return pHead2 if pHead2==None: return pHead1 if pHead1.val<pHead2.val: newHead=pHead1 pHead1=pHead1.next newHead.next=self.Merge(pHead1, pHead2) else: newHead=pHead2 pHead2=pHead2.next newHead.next=self.Merge(pHead1, pHead2) return newHead
    #递归比较复杂,可以搭配debug:
    a1=ListNode(1) b1=ListNode(3) c1=ListNode(5) a2=ListNode(2) b2=ListNode(4) c2=ListNode(6) a1.next=b1 b1.next=c1 a2.next=b2 b2.next=c2 c=Solution() c.Merge(a1,a2)
    #非递归法
    #
    -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): newHead=ListNode(0) #随便找个头节点 tmp=newHead #记录当前插入位置的指针 while pHead1 and pHead2: if pHead1.val<pHead2.val: tmp.next=pHead1 pHead1=pHead1.next else: tmp.next=pHead2 pHead2=pHead2.next tmp=tmp.next if pHead1: tmp.next=pHead1 if pHead2: tmp.next=pHead2 return newHead.next
  • 相关阅读:
    layer ----- 弹层
    php start
    node.js使用iconv-lite和zlib解决gzip压缩和gbk乱码
    AngularJS中promise的使用
    AngularJS中的$routeProvider
    AngularJS入门教程记录
    AngularJS中的$resource
    Javascript原型易错点记录
    触屏相关事件问题记录
    图片预加载
  • 原文地址:https://www.cnblogs.com/foolangirl/p/14002127.html
Copyright © 2011-2022 走看看