-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMiddleOfTheLinkedList.py
80 lines (60 loc) · 1.97 KB
/
MiddleOfTheLinkedList.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# -*- coding: utf-8 -*-
# @File : MiddleOfTheLinkedList.py
# @Date : 2021-02-19
# @Author : tc
"""
876. 链表的中间结点
给定一个头结点为 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,我们返回第二个结点。
提示:
给定链表的结点数介于 1 和 100 之间。
参考:https://leetcode-cn.com/problems/middle-of-the-linked-list/solution/kuai-man-zhi-zhen-zhu-yao-zai-yu-diao-shi-by-liwei/
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create_linked_list(nums):
if len(nums) == 0:
return None
head = ListNode(nums[0])
cur = head
for i in range(1, len(nums)):
cur.next = ListNode(nums[i])
cur = cur.next
return head
def print_linked_list(list_node):
if list_node is None:
return
cur = list_node
while cur:
print(cur.val, '->', end=' ')
cur = cur.next
print('null')
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
if not head:
return head
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow
if __name__ == '__main__':
nums = [1, 2, 3, 4, 5, 6, 7, 8]
head = create_linked_list(nums)
solution = Solution()
result = solution.middleNode(head)
print('结果:')
print_linked_list(result)