原题
https://leetcode.cn/problems/reorder-list/description/
思路
列表+虚拟节点
复杂度
时间:O(n)
空间:O(n)
Python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
arr = []
while head:
arr.append(head)
head = head.next
l, r = 0, len(arr) - 1
dummy = p = ListNode(-1, head)
i = 0
while l <= r:
if i % 2 == 0:
p.next = arr[l]
l += 1
else:
p.next = arr[r]
r -= 1
p = p.next
i += 1
p.next = None
Go代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reorderList(head *ListNode) {
// 切片储存节点
arr := []*ListNode{}
for head != nil {
arr = append(arr, head)
head = head.Next
}
l, r := 0, len(arr)-1
dummy := &ListNode{Val: -1, Next: head}
p := dummy
i := 0
for l <= r {
if i%2 == 0 {
p.Next = arr[l]
l++
} else {
p.Next = arr[r]
r--
}
p = p.Next
i++
}
p.Next = nil
}
1702

被折叠的 条评论
为什么被折叠?



