Leetcode刷題筆記之 鍊錶 總結

2021-10-10 15:06:15 字數 2847 閱讀 9740

[21. 合併兩個有序鍊錶](

[2. 兩數相加](

[61. 旋轉鍊錶](

可見,如果經常需要新增或刪除結點,鍊錶更好,經常按索引訪問元素,陣列更好

class

solution

:def

mergetwolists

(self, l1: listnode, l2: listnode)

-> listnode:

# 設定合併後的表頭

new_head = listnode(-1

) head = new_head

# l1 和 l2總有乙個會先走到頭

while l1 and l2:

if l1.val < l2.val:

head.

next

= l1

l1 = l1.

next

else

: head.

next

= l2

l2 = l2.

next

head = head.

next

# 此時只有一條鍊錶走完,剩下的鍊錶直接拼接在最後面即可

if l1:

head.

next

= l1

else

: head.

next

= l2

return new_head.

next

class

solution

:def

addtwonumbers

(self, l1: listnode, l2: listnode)

-> listnode:

# 用0補齊短鍊表

p1 = l1

p2 = l2

prev_p1 =

none

prev_p2 =

none

while p1 or p2:

ifnot p1 and p2:

prev_p1.

next

= listnode(0)

p1 = prev_p1.

next

ifnot p2 and p1:

prev_p2.

next

= listnode(0)

p2 = prev_p2.

next

if p1 and p2:

prev_p1 = p1

prev_p2 = p2

p1 = p1.

next

p2 = p2.

next

# 齊位運算

p1 = l1

p2 = l2

carry =

0 prev_p1 =

none

while p1 and p2:

ifcarry =

(p1.val + p2.val + carry)

>=

10 p1.val =

(p1.val + p2.val + carry)%10

if ifcarry:

carry =

1else

: carry =

0 prev_p1 = p1

p1 = p1.

next

p2 = p2.

next

ifnot p1 and carry ==1:

prev_p1.

next

= listnode(1)

return l1

# definition for singly-linked list.

# class listnode:

# def __init__(self, val=0, next=none):

# self.val = val

# self.next = next

class

solution

:def

rotateright

(self, head: listnode, k:

int)

-> listnode:

ifnot head or

not head.

next

:return head

# 確定長度

p1 = head

length =

0while p1:

length +=

1 p1 = p1.

next

pre_tail =

none

tail = head

for _ in

range

(k%length)

:while tail.

next

: pre_tail = tail

tail = tail.

next

pre_tail.

next

=none

# 尾結點新增進頭結點

tail.

next

= head

head = tail

return head

Leetcode刷題鍊錶之環形鍊錶

給定乙個鍊錶,判斷鍊錶中是否有環。定義兩個指標,從頭節點開始,兩個指標都向右移動,但是設定他們的移動速度不一樣,如果為環形鍊錶,則指標肯定會相遇。若為直鏈表,兩個指標至少有乙個為空。definition for singly linked list.class listnode public cla...

Leetcode鍊錶刷題之 206 反轉鍊錶

反轉乙個單鏈表。示例 輸入 1 2 3 4 5 null 輸出 5 4 3 2 1 null 高階 你可以迭代或遞迴地反轉鍊錶。你能否用兩種方法解決這道題?解題思路 原地旋轉鍊錶,可以構建兩個指標,乙個指向當前結點的前乙個,乙個指向當前的結點,每次迴圈的時候,找到當前鍊錶的下乙個,在翻轉的過程中,將...

LeetCode刷題筆記 328 奇偶鍊錶

給定乙個單鏈表,把所有的奇數節點和偶數節點分別排在一起。請注意,這裡的奇數節點和偶數節點指的是節點編號的奇偶性,而不是節點的值的奇偶性。請嘗試使用原地演算法完成。你的演算法的空間複雜度應為 o 1 時間複雜度應為 o nodes nodes 為節點總數。示例 輸入 2 1 3 5 6 4 7 nul...