Leetcode 876. 链表的中间结点 (每日一题 20210918)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 876. 链表的中间结点 (每日一题 20210918)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個頭結點為 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,我們返回第二個結點。鏈接:https://leetcode-cn.com/problems/middle-of-the-linked-listclass Solution:def midNode(self, head:ListNode)->ListNode:cur = headnex = head.nextcount, i = 1, 0while nex:nex = nex.nextcount += 1nex = head.nextwhile i < count//2:cur = nexnex = nex.nexti += 1return cur
總結
以上是生活随笔為你收集整理的Leetcode 876. 链表的中间结点 (每日一题 20210918)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 剑指 Offer 21
- 下一篇: Leetcode 45. 跳跃游戏 II