lintcode鍊錶的中點

2021-09-29 05:59:47 字數 2703 閱讀 5616

第一次寫的,如果fast.next是none,那麼fast.next.next會報錯

def

middlenode

(self, head)

:# write your code here

i =0if head.val !=

none

: slow = head

fast = head

while fast.

next

.val !=

none

: slow = slow.

next

fast = fast.

next

while fast.

next

.val !=

none

: fast = fast.

next

return slow.val

else

:return

none

第二次寫的。需要先判斷fast.next.next不為none,再給slow往下走一步。判斷鍊錶為空,應該判斷head是否為none ,不應該判斷head.next。

"""

definition of listnode

class listnode(object):

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

self.val = val

self.next = next

"""class

solution

:"""

@param head: the head of linked list.

@return: a middle node of the linked list

"""defmiddlenode

(self, head)

:# write your code here

ifnot head.

next

:return

none

else

: slow = head

fast = head

while fast.

next

: slow = slow.

next

fast = fast.

next

while fast.

next

: fast = fast.

next

break

return

(slow)

第三次

"""

definition of listnode

class listnode(object):

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

self.val = val

self.next = next

"""class

solution

:"""

@param head: the head of linked list.

@return: a middle node of the linked list

"""defmiddlenode

(self, head)

:# write your code here

ifnot head:

return

none

else

: slow = head

fast = head

while fast.

next

: fast = fast.

next

if fast.

next

: slow = slow.

next

fast = fast.

next

return

(slow)

通過

檢視別人的寫法,先判斷fast.next,用and連線判斷fast.next.next。一條就搞定。

class

solution

:"""

@param head: the head of linked list.

@return: a middle node of the linked list

"""defmiddlenode

(self, head)

:# write your code here

ifnot head:

return

none

else

: slow,fast = head,head

while fast.

next

and fast.

next

.next

: slow = slow.

next

fast= fast.

next

.next

return slow

lintcode演算法題之228 鍊錶的中點

找鍊錶的中點。樣例 1 輸入 1 2 3 輸出 2 樣例解釋 返回中間節點的值樣例 2 輸入 1 2 輸出 1 樣例解釋 如果長度是偶數,則返回中間偏左的節點的值。區 definition for listnode public class listnode public class solutio...

鍊錶的中點 快慢指標

include include 鍊錶的操作 也可以直接使用stl中的雙向鍊錶結構list。typedef struct listnode listnode,plistnode 快速尋找鍊錶的中間節點 注 對於尋找鍊錶倒數第n個節點也是同樣的流程 listnode findmidnodeinlist ...

鍊錶常用技巧 鍊錶逆序 鍊錶中點

給定乙個鍊錶,一般的逆序的方法要設定三個指標,這種操作很繁瑣,下面總結一種簡單的方法 為鍊錶設定乙個頭結點,然後head後面的節點依次的插入到head結點之前。最後完成鍊錶的逆序。實現 listnode reverselist listnode head while return dummy.nex...