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

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

    参考博客:https://blog.csdn.net/qq_18254385/article/details/94558439

    原博客有些错误!!!

    解法1:

    (容器法)首先将两个链表保存到容器内,然后使用排序算法进行排序,之后重新整理每个节点的next指向。

    class ListNode:
        def __init__(self,x):
            self.val=x
            self.next=None
    
    def Merge(pHead1,pHead2):
        if pHead1==None and pHead2==None:
            return None
        elif pHead1==None and pHead2!=None:
            return pHead2
        elif pHead1!=None and pHead2==None:
            return pHead1
        stack=[]
        while pHead1:
            stack.append(pHead1)
            pHead1=pHead1.next
        while pHead2:
            stack.append(pHead2)
            pHead2=pHead2.next
    
        for i in range(len(stack)):
            for j in range(len(stack)-1-i):
                if stack[j].val > stack[j+1].val:
                    stack[j],stack[j+1]=stack[j+1],stack[j]
    
        stack[-1].next=None
        for i in range(len(stack)-1):
            stack[i].next=stack[i+1]
    
        return stack[0]
    
    a=ListNode(1)
    b=ListNode(2)
    c=ListNode(3)
    d=ListNode(4)
    e=ListNode(5)
    f=ListNode(6)
    a.next=c
    c.next=e
    
    b.next=d
    d.next=f
    
    node=Merge(a,b)
    while node:
        print(node.val)
        node=node.next

    解法2:

    (指针法)

    1、使用两个指针同时指向两个不同的头结点,另外创建一个新链表用于连接输出的节点;

    2、比较两个指针所指向节点的值得大小,将小的节点输出连接到新链表后面,同时该节点的指针指向下一个节点;

    3、不断指向上一步,直到其中一个链表被输出完毕,那么另一个链表直接连接在新链表后面

    4、返回新链表的第二个节点

    class ListNode:
        def __init__(self,x):
            self.val=x
            self.next=None
    def Merge(pHead1, pHead2):
            # write code here
            mergeHead = ListNode(90)
            p = mergeHead
            while pHead1 and pHead2:
                if pHead1.val >= pHead2.val:
                    mergeHead.next = pHead2
                    pHead2 = pHead2.next
                else:
                    mergeHead.next = pHead1
                    pHead1 = pHead1.next
                      
                mergeHead = mergeHead.next
            if pHead1:
                mergeHead.next = pHead1
            elif pHead2:
                mergeHead.next = pHead2
            return p.next
    
    
    
    a=ListNode(1)
    b=ListNode(2)
    c=ListNode(3)
    d=ListNode(4)
    e=ListNode(5)
    f=ListNode(6)
    a.next=c
    c.next=e
    
    b.next=d
    d.next=f
    
    node=Merge(a,b)
    while node:
        print(node.val)
        node=node.next
  • 相关阅读:
    Cookie和Seesion
    Forms组件
    分页器组件
    关于Django的Ajax操作
    Oracle常用数据库表操作
    redis的缓存穿透 缓存并发 缓存失效
    Struts2的拦截器
    Struts2的各种标签库
    Struts2基础知识
    Java常用数据结构和算法
  • 原文地址:https://www.cnblogs.com/pythonbigdata/p/12343262.html
Copyright © 2011-2022 走看看