给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
思路
通过快慢指针将链表分为前后两半部分两个链表,将后半部分反转,两个链表的元素交替进行连接
代码
def reorderList(self, head):
if(head==None):return
slow=head
fast=head
while fast.next!=None and fast.next.next!=None:
slow=slow.next
fast=fast.next.next
B=slow.next
slow.next=None#将链表分为两部分
C=None
while B!=None:
N=B.next
B.next=C
C=B
B=N
B=C#后半部分反转
A=head.next
N=head
i=1
while A!=None or B!=None:#交替连接
if i%2==0:
N.next=A
A=A.next
else:
N.next=B
B=B.next
N=N.next
i=i+1