leetcode 143 重排鍊錶

2021-10-08 22:43:05 字數 3001 閱讀 1077

給定乙個單鏈表 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.
空間複雜度o(n

)o(n)

o(n)

版:用1個雙端佇列儲存鍊錶,然後每次從頭pop乙個,從尾pop乙個,依次連線

看了題解,有個空間複雜度o(1

)o(1)

o(1)

版的解法。先用快慢指標找出鍊錶的中點,然後反轉後半段鍊錶,再把前半段和後半段鍊錶合併成1個即可。

注意用快慢指標找到中點後,不管是奇數個節點還是偶數個節點,要反轉的都是slow指向的後乙個節點開始的鍊錶。

# 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: listnode)

->

none

:"""

do not return anything, modify head in-place instead.

"""ret_head = listnode(-1

) dequeue = collections.deque(

) p = head

while p:

p = p.

next

p = ret_head

pop_from_head =

true

while dequeue:

if pop_from_head:

next_node = dequeue.popleft(

) pop_from_head =

false

else

: next_node = dequeue.pop(

) pop_from_head =

true

p.next

= next_node

p = p.

next

p.next

=none

return ret_head.

next

原地版:

# 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: listnode)

->

none

:"""

do not return anything, modify head in-place instead.

"""ifnot head:

return

none

defreverse_list

(head: listnode, end)

-> listnode:

prev, p = end, head

while p:

pn = p.

next

p.next

= prev

prev, p = p, pn

return prev

slow, fast = head, head

while fast and fast.

next

: slow = slow.

next

fast = fast.

next

.next

reverse_head = reverse_list(slow.

next

,none

) slow.

next

=none

head1, head2 = head, reverse_head

ret_head = listnode(-1

) choose_head1 =

true

p = ret_head

while head1 and head2:

if choose_head1:

p.next

= head1

head1 = head1.

next

choose_head1 =

false

else

: p.

next

= head2

head2 = head2.

next

choose_head1 =

true

p = p.

next

if head1:

p.next

= head1

if head2:

p.next

= head2

return ret_head.

next

Leetcode 143 重排鍊錶

給定乙個單鏈表 l l0 l1 l n 1 ln 將其重新排列後變為 l0 l n l1 l n 1 l2 l n 2 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。解題思路 前一半 0,size 1 2 的結點位址進入佇列,先進先出,後一半 size 1 2,size 的結點入棧,...

LeetCode 143 重排鍊錶

給定乙個單鏈表 l l0 l1 l n 1 ln 將其重新排列後變為 l0 l n l1 l n 1 l2 l n 2 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。解題思路 首先想到的是找到要插入的元素,壓入堆疊,彈出時剛好為期望的順序,然後插入對應位置。再換一種思路,找到待插入節...

leetcode143 重排鍊錶

給定乙個單鏈表 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...