Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
这个题思路上不难,稍微复杂一点,分三步(以1->2->3->4为例):
1.找到中间的点,把两个链表断开 1->2 3->4
2.把后面的链表倒置 1->2 4->3
3.把两个链表交叉连接起来 1->4->2->3
代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
slow = fast = head
if not head or not head.next:return head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
middle = slow.next
slow.next = None
prev=None
while middle:
cur = middle
middle = middle.next
cur.next = prev
prev = cur
rhead = head
while head and prev:
p=head.next
q=prev.next
head.next = prev
prev.next = p
head=p
prev=q
return rhead
需要注意的是while fast and fast.next:我之前想法是可以只写while fast.next:,但这样是不对的,因为fast如果为None会报错