链表重排序
题目描述:
给定链表 Lo一>L1一>L2… Ln-1一>Ln,把链表重新排序为 Lo >Ln一>L1一>Ln-1->L2一> Ln-2…。要求:(l)在原来链表的基础上进行排序,即不能申请新的结点;(2)只能修改结点的 next 域,不能修改数据域。
解题思路:
- 找出链表的中间节点,分成前后两个链表(可使用快慢指针法)
- 对后半部分链表进行逆序
- 按照题目要求合并前后两个链表
实现方法如下图:
完整代码:
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)