zoukankan      html  css  js  c++  java
  • 链表问题(8)----合并

    一、题目:合并两个有序的单链表

    思路:时间复杂度O(M+N),空间复杂度O(1)

     简单来说就是在原来的链表上采用三个指针来操作两个链表。

    若是合并两个无序链表成有序链表,先将两个链表用冒泡或快排等方法排序,再合并。

    代码:

    class Node:
        def __init__(self,value):
            self.val = value
            self.next = None
    def mergeList(l1,l2):
        if not l1 or not l2:
            return l1 if l1 else l2
        cur1 , cur2 = l1 , l2
        head = cur1 if cur1.val < cur2.val else cur2
        cur = None
        while cur1 and cur2:
            tail = cur
            cur = cur1 if cur1.val < cur2.val else cur2
            cur1 = cur1.next if cur == cur1 else cur1
            cur2 = cur2.next if cur == cur2 else cur2
            if tail:
                tail.next = cur
        tail.next.next = cur1 if cur1 else cur2
        return head
    
        
        
    head = Node(1)
    p = head
    for i in range(2,4):
        p.next = Node(i)
        p = p.next
    head1 = Node(1)
    p = head1
    for i in range(2,5):
        p.next = Node(i)
        p = p.next
    mergeList(head,head1)

    二、题目:按照左右半区的方式重新组合单链表

    思路:时间复杂度O(N),空间复杂度O(1)

    简单来说就是将原链表拆分成左右半区,再合并。

    代码:

    class Node:
        def __init__(self,value):
            self.val = value
            self.next = None
    #拆分链表
    def relocate(head):
        if not head or not head.next:
            return head
        slow = head
        fast = head.next
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        right = slow.next
        slow.next = None
        mergeLR(head,right)
    #合并链表
    def mergeLR(left,right):
        if not left or not right:
            return left if left else right
        head = left
        cur =head
        while left:
            left = left.next
            cur.next = right 
            cur = cur.next
            right = right.next
            cur.next = left
            cur = cur.next
        return head
    head = Node(1)
    p = head
    for i in range(2,9):
        p.next = Node(i)
        p = p.next
    res = relocate(head)
  • 相关阅读:
    无法直接启动带有类库输出类型的项目
    2个页面传值方法
    vs2005 无法附加 绑定句柄无效 解决办法
    认识serializable,序列化
    jsp 连接sql 2008
    有进步,嘎嘎....
    找不到存储过程'dbo.aspnet_CheckSchemaVersion'
    BackOffice Common中实现的相关功能
    MVC中Action相关方法的建议
    mysql的数据库相关维护操作:重启、修改连接数、删除连接
  • 原文地址:https://www.cnblogs.com/Lee-yl/p/9785703.html
Copyright © 2011-2022 走看看