题目链接:
分三步:
- 利用快慢指针,找到原链表的中点
- 将后半部分链表进行翻转
- 将反转之后的后半部分链表依次插入前半部分链表的间隔中。
python实现:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @return void
#
class Solution:
def findMidNode(self, head): # 找中点
fast, slow = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
# 当跳出while循环时,slow指向的正是原链表的中点,fast指向的是原链表的最后一个节点
midNextNode = slow.next
slow.next = None # 与firstHalf断开,只返回secondHalf的head
return midNextNode
def reverseSecondHalf(self, secondHalfHead): # 翻转
pre = None
cur = secondHalfHead
while cur:
curNext = cur.next
cur.next = pre
pre = cur
cur = curNext
rSecondHalfHead = pre # 对后半部分翻转后的链表的头节点
return rSecondHalfHead
def reorderList(self , head ): # 重排
# write code here
if head == None:
return
secondHalfHead = self.findMidNode(head)
rSecondHalfHead = self.reverseSecondHalf(secondHalfHead)
temp1, temp2 = head, rSecondHalfHead
while temp1 and temp2:
temp1Next = temp1.next
temp1.next = temp2
temp2Next = temp2.next
temp2.next = temp1Next
temp1 = temp1Next
temp2 = temp2Next