程序员面试算法宝典-1.4 如何对链表进行重新排序

题目描述:
给定链表L0->L1->L2...->Ln,把链表重新排序为L0->Ln->l1->Ln-1->L2->Ln-2...。要求:(1)在原来链表的基础上进行排序,
既不能申请新的结点;(2)只能修改结点的next域,不能修改数据域。
# 声明类结点
class LNode:
    def __init__(self):
        self.data = None # 数据域
        self.next = None # 指针域

# 找到链表的中间点
def FindMiddleNode(head):
    if head is None or head.next is None:
        return head
    # 遍历列表的时候每次向前走两步
    fast = head
    # 遍历列表的时候每次向前走一步
    slow = head
    slowPre = head
    # 当fast到链表尾时,slow恰好指向链表的中间结点
    while fast is not None and fast.next is not None:
        slowPre = slow
        slow = slow.next
        fast = fast.next.next
    # 把链表断开成两个独立的子链表
    slowPre.next = None
    return slow

# 对不带头结点的单链表翻转
def Reverse(head):
    if head==None or head.next==None:
        return head
    # 前驱结点
    pre = head
    # 当前结点
    cur = head.next
    # 后继结点
    next = cur.next
    pre.next = None
    # 使当前遍历到的结点cur指向其前驱结点
    while cur is not None:
        next = cur.next
        cur.next = pre
        pre = cur
        cur = next
    return pre

# 对链表进行排序
def Reorder(head):
    if head==None or head.next==None:
        return
    # 前半部分链表第一个结点
    cur1 = head.next
    mid = FindMiddleNode(head.next)
    # 后半部分链表逆序后的第一个结点
    cur2 = Reverse(mid)
    tmp = None
    # 合并两个链表
    while cur1.next is not None:
        tmp = cur1.next
        cur1.next = cur2
        cur1 = tmp
        tmp = cur2.next
        cur2.next = cur1
        cur2 = tmp
    cur1.next = cur2


if __name__=="__main__":
    i = 1
    head = LNode() # 头结点
    tmp = head
    while i<8:
        cur = LNode()
        cur.data = i
        tmp.next = cur
        tmp = tmp.next
        i += 1
    print("排序前:")
    cur = head.next
    while cur!=None:
        print(cur.data)
        cur = cur.next
    Reorder(head)
    print("排序后:")
    cur = head.next
    while cur!=None:
        print(cur.data)
        cur = cur.next

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值