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)
  • 相关阅读:
    MIN (Transact-SQL)【转】
    ROW_NUMBER() OVER函数的基本用法用法【转】
    读取文件中的内容
    Stopwatch 和TimeSpan介绍【转】
    TimeSpan类【转】
    Stopwatch 类【转】
    ToString()使用方法
    用c#读取文件内容中文是乱码的解决方法:
    vue实现购物车和地址选配(二)
    vue实现购物车和地址选配
  • 原文地址:https://www.cnblogs.com/Lee-yl/p/9785703.html
Copyright © 2011-2022 走看看