给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
输入:head = [1,2,3,4]
输出:[1,4,2,3]
构建一个 tail 指针 每次操作如下
head.next = tail
tail.next = head.next
实际可以给节点增加一个 prev 属性模拟 head.next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if head is None or head.next is None:
return
tail = head
tail.prev = None
length = 1
while tail.next is not None:
tail.next.prev = tail
tail = tail.next
length += 1
res_len = 1
while True:
t_head = head.next
t_tail = tail.prev
head.next = tail
res_len += 1
if res_len >= length:
tail.next = None
return
tail.next = t_head
res_len += 1
if res_len >= length:
t_head.next = None
return
head = t_head
tail = t_tail