876. 鏈表的中間結點
題目:
給定一個帶有頭結點 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 之間。
首先python的鏈表是怎麼實現的呢?之前只在C語言課堂上接觸過鏈表。
後來在搜索之後知道單鏈表創建其實還是很簡單的:
class Node:
def __init__(self,data,next=None):
self.data = data
self.next = next
node1 = Node(1)
node2 = Node(2)
node1.next = node2
這樣就可以創建一個單鏈表了。
我一開始只能想到最簡單的辦法,先找到總長度,然後取中值,之後再找到該位置的值。
class Solution:
def hasCycle(self, head):
if head is None:
return null
end = head
count = 1
while end.next:
end = end.next
count = count + 1
count = count/2 + 1
index = 1
midd = head
while index < count:
midd = midd.next
index = index + 1
return midd
後來在評論區看到了快慢指針的做法,快指針的速度是慢指針的兩倍,快指針走到鏈表末尾的時候,慢指針正好走到一半。
class Solution:
def hasCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow