[LeetCode Python 3] 876. Middle of the Linked List(鏈表的中間結點)

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

若是有兩個中間結點,則返回第二個中間結點。指針

示例 1:code

輸入:[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,咱們返回第二個結點。

提示:it

  • 給定鏈表的結點數介於 1100 之間。

思路:io

設置兩個指向頭節點的快慢指針,快指針每次走兩步,慢指針每次走一步,當快指針到達最後結點或爲空時,慢指針指向的就是中間結點 。class

解題代碼Python 3:List

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pa=pb=head
        while pa and pb.next:
            if pb.next.next==None:
                return pa.next
            pa=pa.next
            pb=pb.next.next
        return pa
相關文章
相關標籤/搜索