zoukankan      html  css  js  c++  java
  • 1.4链表重排序

    链表重排序

    题目描述:

    给定链表 Lo一>L1一>L2… Ln-1一>Ln,把链表重新排序为 Lo >Ln一>L1一>Ln-1->L2一> Ln-2…。要求:(l)在原来链表的基础上进行排序,即不能申请新的结点;(2)只能修改结点的 next 域,不能修改数据域。

    解题思路:

    1. 找出链表的中间节点,分成前后两个链表(可使用快慢指针法)
    2. 对后半部分链表进行逆序
    3. 按照题目要求合并前后两个链表

      实现方法如下图:

    完整代码:

    class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next
    
    
    def print_link(head):
        cur = head.next
        while cur is not None:
            print(cur.data, end=' ')
            cur = cur.next
        print()
    
    
    # 找出链表的中间节点
    def findMiddleNode(head):
        if head is None or head.next is None:
            return None
        fast = head
        slow = head
        slowpre = head
        while fast is not None:
            slowpre = slow
            if fast.next is None:
                fast = fast.next
            else:
                fast = fast.next.next
            slow = slow.next
        slowpre.next = None
        return head, slow
    
    
    # 无头结点链表的逆序
    def reverse_link(head):
        pre = head
        cur = head.next
        head.next = None
        while cur.next is not None:
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next
        cur.next = pre
        return cur
    
    
    # 合并前后两个链表
    def merge_link(pre_head, back_head):
        pre = pre_head.next
        cur = back_head
        while pre.next is not None:
            pre_next = pre.next
            cur_next = cur.next
            pre.next = cur
            cur.next = pre_next
            pre = pre_next
            cur = cur_next
        if pre.next is None:
            pre.next = cur
        return pre_head
    
    
    # 构造带头结点的链表
    def con_link(n):
        head = Node()
        cur = head
        for i in range(1, n + 1):
            node = Node(i)
            cur.next = node
            cur = cur.next
        return head
    
    
    if __name__ == '__main__':
        head = con_link(6)
        print_link(head)
        pre_head, back_head = findMiddleNode(head)
        back_head = reverse_link(back_head)
        head = merge_link(pre_head, back_head)
        print_link(head)
    

    运行结果:

  • 相关阅读:
    CodeForces 681D Gifts by the List (树上DFS)
    UVa 12342 Tax Calculator (水题,纳税)
    CodeForces 681C Heap Operations (模拟题,优先队列)
    CodeForces 682C Alyona and the Tree (树上DFS)
    CodeForces 682B Alyona and Mex (题意水题)
    CodeForces 682A Alyona and Numbers (水题,数学)
    Virtualizing memory type
    页面跳转
    PHP Misc. 函数
    PHP 5 Math 函数
  • 原文地址:https://www.cnblogs.com/miao-study/p/11468708.html
Copyright © 2011-2022 走看看