给定一个单链表 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.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if not head:
return None
slow=head
fast=head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
head1=head
head2=slow.next
slow.next = None #不是很清楚这句话的意思
#反转第二条链
cur, pre = head2, None
while cur:
nex = cur.next
cur.next = pre
pre = cur
cur = nex
#交叉
cur1, cur2 = head1, pre
while cur2:
nex1, nex2 = cur1.next, cur2.next
cur1.next = cur2
cur2.next = nex1
cur1, cur2 = nex1, nex2
执行用时: 116 ms, 在Reorder List的Python3提交中击败了95.60% 的用户