码迷,mamicode.com
首页 > 编程语言 > 详细

1.4链表重排序

时间:2019-09-05 18:59:57      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:快慢指针   main   head   back   fast   reverse   turn   上进   http   

链表重排序

题目描述:

给定链表 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)

运行结果:

技术图片

1.4链表重排序

标签:快慢指针   main   head   back   fast   reverse   turn   上进   http   

原文地址:https://www.cnblogs.com/miao-study/p/11468708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!