Skip to content

Commit 415622c

Browse files
authored
Add files via upload
1 parent 37c33a2 commit 415622c

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

876.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.next = None
6+
7+
class Solution:
8+
def middleNode(self, head: ListNode) -> ListNode:
9+
if head.next == None: # 考虑边界情况
10+
return head
11+
if head.next.next == None:
12+
return head.next
13+
# 定义保留头节点
14+
tmp = head
15+
tmp_list = []
16+
while tmp:
17+
tmp_list.append(tmp.val)
18+
tmp = tmp.next
19+
for _ in range(len(tmp_list)//2): # 循环结束正好到达中间位置
20+
head = head.next
21+
return head
22+
'''
23+
题:
24+
输入:[1,2,3,4,5]
25+
输出:此列表中的结点 3 (序列化形式:[3,4,5])
26+
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
27+
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
28+
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
29+
30+
解:
31+
遍历一遍链表,将其保存在数组tmp_list中,中间结点的索引为len(tmp_list) // 2,将指针移到该位置即可。
32+
'''

0 commit comments

Comments
 (0)