Posted on 2022-12-05 11:38
Uriel 阅读(48)
评论(0) 编辑 收藏 引用 所属分类:
数据结构 、
闲来无事重切Leet Code
找到一个链表的中间位置(如果是偶数个元素,找到中间之后的位置),第一遍扫链表计算元素个数,第二遍停在n/2处
1 #876
2 #Runtime: 15 ms
3 #Memory Usage: 13.5 MB
4
5 # Definition for singly-linked list.
6 # class ListNode(object):
7 # def __init__(self, val=0, next=None):
8 # self.val = val
9 # self.next = next
10 class Solution(object):
11 def middleNode(self, head):
12 """
13 :type head: ListNode
14 :rtype: ListNode
15 """
16 st = head.next
17 n = 1
18 while st:
19 st = st.next
20 n += 1
21 n = n//2 + 1
22 st = head
23 for i in range(n - 1):
24 st = st.next
25 return st