File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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
+ '''
You can’t perform that action at this time.
0 commit comments