给定一个单链表:L0->L1->L3...Ln-1->Ln
变为L0->Ln->L1...
分析:
实际上就是首先对链表进行对半分。把后面一半逆序排序,之后和前面一部分进行交叉排列。
这里面对链表进行对半分比较难解决,回顾前面几道题:快慢指针。
使用一个快指针,一次走两步,一个慢指针一次走一步。
他们同时出发,则在快指针到链表尾部的时候,慢指针会指向链表对半分之后的第二部分子链表的表头。
算法伪代码就不写了上面的分析已经比较明晰:
python实现如下:
class Solution:
def reverse(self,head):
if head == None or head.next == None:
return head
pre = head
cur = head.next
nex = head.next.next
pre.next = None
cur.next = pre
while nex != None:
pre = cur
cur = nex
nex= nex.next
cur.next = pre
return cur
def merge(self,h1,h2):
tmp1 = h1
tmp2 = h2
while tmp1 != None and tmp2 != None:
tmp = tmp1
tmp1 = tmp1.next
tmp.next = tmp2
tmp = tmp2
tmp2 =tmp2.next
tmp.next = tmp1
return h1
def reorderList(self,head):
if head == None or head.next == None:
return head
first = head.next
second = head.next.next
while second != None:
if second.next == None:
break
first = first.next
second = second.next.next
second = first.next
first.next = None
second = self.reverse(second)
head = self.merge(head,second)
return head