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
  • 相关阅读:
    关于华为x1 7.0无法从eclipse发布的更新as发布的apk
    2015-10-29
    Android Exception18(Stuido debug .....)
    阿里巴巴校招运营专员笔试题
    业务性产品经理(商业领域)笔试题
    Android编程之常识
    2015-08-24
    What most young programmers need to learn
    hdu 1556 Color the ball
    跟着实例学习设计模式(3)-工厂方法(创建型)
  • 原文地址:https://www.cnblogs.com/foolangirl/p/14002127.html
Copyright © 2011-2022 走看看