题目描述:
给定链表L0 —> L1 —> L2 .....Ln-1 —> Ln,把链表重新排序为L0 —> Ln —> L1 —> Ln-1 —>L2 —> Ln-2......
要求:
(1)在原来链表的基础上进行排序,即不能申请新的节点
(2)只能修改节点的next域,不能修改数据域
解题思路分析:
(1)首先找到链表的中间节点
(2)对链表的后半部分进行逆序
(3)把链表的前半部分和逆序后的后半部分进行合并
代码实现:
class LNode:
def __init__(self, item):
self.data = item
self.next = None
def FindMiddleNode(head):
if head is None or head.next is None:
return head
fast = head
slow = head
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 is None or head.next is None:
return head