思路是,先用快慢指针找到中点位置,把链表一分为二,把第二个链表反转,依次插入第一个链表中。
具体操作中有以下需要注意的地方:
1.如果是空,一个节点,两个节点的情况下,不用重排,直接返回;
2.反转链表这一步,注意判断条件
3.插入链表中这一步,注意停止条件。判断条件设置在第二个链表上,当一次插入结束后,如果第二个链表里已经没有元素了,即curNode == None,跳出循环
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self , head ):
# write code here
if head is None:
return
if head.next is None or head.next.next is None:
return head
fast = head
slow = head
while fast is not None:
if fast.next is None:
break
elif fast.next.next is None:
break
fast = fast.next.next
slow = slow.next
l2 = slow.next
slow.next = None
l1 = head
def researve(head):
pre = None
cur = head
tmp = head.next
while cur is not None:
cur.next = pre
pre = cur
if tmp is None:
break
cur = tmp
# if tmp.next is None:
# break
tmp = tmp.next
return cur
l1cur = l1
l1then = l1.next
l2cur = researve(l2)
l2then = l2cur.next
while 1:
l1cur.next = l2cur
l2cur.next = l1then
l1cur = l1then
l2cur = l2then
if l2cur is None:
break
l1then = l1then.next
l2then = l2then.next
return head