876 鍊錶的中間結點

2021-09-12 21:55:27 字數 1426 閱讀 3260

給定乙個帶有頭結點 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,我們返回第二個結點。

給定鍊錶的結點數介於 1 和 100 之間。

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

mid=[1,head]

end=[1,head]

while not end[1].next == none:

end[0]+=1

end[1]=end[1].next

while end[0]>mid[0]*2:

mid[0]+=1

mid[1]=mid[1].next

if end[0]%2:

return mid[1]

else:

return mid[1].next

借鑑。。

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

a=b=head

while b and b.next:

a=a.next

b=b.next.next

return a

另外:

先遍歷一遍整個鏈得到鏈長,然後再遍歷到鏈中間返回

876 鍊錶的中間結點

題目描述 給定乙個帶有頭結點 head 的非空單鏈表,返回鍊錶的中間結點。如果有兩個中間結點,則返回第二個中間結點。示例 1 輸入 1,2,3,4,5 輸出 此列表中的結點 3 序列化形式 3,4,5 返回的結點值為 3 測評系統對該結點序列化表述是 3,4,5 注意,我們返回了乙個 listnod...

876 鍊錶的中間結點

給定乙個帶有頭結點 head 的非空單鏈表,返回鍊錶的中間結點。如果有兩個中間結點,則返回第二個中間結點。該題目來自力扣題庫 示例示例 1 輸入 1,2,3,4,5 輸出 此列表中的結點 3 序列化形式 3,4,5 返回的結點值為 3 測評系統對該結點序列化表述是 3,4,5 注意,我們返回了乙個 ...

876 鍊錶的中間結點

分析題目,看到單鏈表且求中間結點,立即推!快慢指標法!用兩個指標 last 與 fast 一起遍歷鍊錶。last 一次走一步,fast 一次走兩步。那麼當 fast 到達鍊錶的末尾時,last 必然位於中間。public class main public static void main stri...