hugo-blog/content/posts/2020-03-26-leetcode-876.md
Ching 5ba7024532 feat(content; layouts; static): migrate hexo blog. add new theme fuji.
migrate hexo blog. add new theme fuji.

Signed-off-by: Ching <loooching@gmail.com>
2022-02-07 23:38:40 +08:00

1.3 KiB
Raw Blame History

title date tags categories
leetcode-876 2020-03-26 21:18:41
leetcode
leetcode

876. 链表的中间结点

题目

思路是遍历一遍得到整个链表,讲每个 node 放进一个 list就可以通过下标得到中间的。

# 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:
    l = []
    n = head
    while n.next:
      l.append(n)
      n = n.next
    l.append(n)
    return l[len(l)//2]

 #44 ms	13.7 MB

看官方解答,还有一个骚操作,通过两个速度不一样的指针,一个一次走一步,一个两次走一步,快的走到底时,慢的就在中间了。

class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow

作者LeetCode-Solution
链接https://leetcode-cn.com/problems/middle-of-the-linked-list/solution/lian-biao-de-zhong-jian-jie-dian-by-leetcode-solut/
来源力扣LeetCode
著作权归作者所有商业转载请联系作者获得授权非商业转载请注明出处