题目描述:
给定链表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