leetcode鍊錶題心得

2021-09-12 00:02:11 字數 2805 閱讀 9699

給定乙個排序鍊錶,刪除所有重複的元素,使得每個元素只出現一次。

示例 1:

輸入:1->1->2輸出:1->2
示例 2:

輸入:1->1->2->3->3輸出:1->2->3
思路一:直接方法:

# definition for singly-linked list.

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def deleteduplicates(self, head: listnode) -> listnode:

if head:

cur = head

while cur and cur.next:

if cur.val == cur.next.val:

cur.next = cur.next.next

else:

cur = cur.next

return head

思路二:遞迴法

# definition for singly-linked list.

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def deleteduplicates(self, head: listnode) -> listnode:

if head:

cur = head

if cur.next is none:

return cur

if cur.val == cur.next.val:

cur.next = cur.next.next

cur = self.deleteduplicates(cur)

return cur

else:

cur.next = self.deleteduplicates(cur.next)

return cur

給定乙個帶有頭結點head的非空單鏈表,返回鍊錶的中間結點。

如果有兩個中間結點,則返回第二個中間結點。

示例 1:

輸入:[1,2,3,4,5]

輸出:此列表中的結點 3 (序列化形式:[3,4,5])

返回的結點值為 3 。 (測評系統對該結點序列化表述是 [3,4,5])。

注意,我們返回了乙個 listnode 型別的物件 ans,這樣:

ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = null.

示例 2:

輸入:[1,2,3,4,5,6]

輸出:此列表中的結點 4 (序列化形式:[4,5,6])

由於該列表有兩個中間結點,值分別為 3 和 4,我們返回第二個結點。

思路一:將鍊錶中的值放在陣列中,使用切片方式獲得後半部分值。

# definition for singly-linked list.

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def middlenode(self, head: listnode) -> listnode:

if head.next is none:

return head

else:

list=

cur = head

while cur is not none:

cur = cur.next

return list[int(len(list)/2):]

思路二:快慢指標法,慢指標每次走一步,快指標每次走兩步,當快指標走完,返回慢指標。

# definition for singly-linked list.

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def middlenode(self, head: listnode) -> listnode:

if head.next is none:

return head

else:

slow = head

fast = head

while fast and fast.next:

slow = slow.next

fast = fast.next.next

return slow

LeetCode題 旋轉鍊錶

原題 給定乙個鍊錶,旋轉鍊錶,將鍊錶每個節點向右移動 k 個位置,其中 k 是非負數。示例 1 輸入 1 2 3 4 5 null,k 2 輸出 4 5 1 2 3 null 解釋 向右旋轉 1 步 5 1 2 3 4 null 向右旋轉 2 步 4 5 1 2 3 null 示例 2 輸入 0 1...

LeetCode 鍊錶題總結

最近花了幾天時間,將鍊錶題除帶鎖外的題目做完了,下面對鍊錶題部分題目進行總結和分析。1 鍊錶反轉 2 快慢指標 遇到一些需要找到鍊錶的中點問題時,可能會有鍊錶長度為奇數或者偶數的情況,當長度為偶數時,模板裡面 prev 為第乙個中點,slow 為第二個中點,長度為奇數時 slow 為鍊錶的中點。1....

LeetCode鍊錶簡單題

一 21合併兩個有序鍊錶 如下 class solution def mergetwolists self,l1 listnode,l2 listnode listnode 首先對特殊情況進行處理,l1 l2 為空的時候 ifnot l1 and l2 這個表示式的意思只要l1 l2 不全為真就符合...