-
Notifications
You must be signed in to change notification settings - Fork 0
/
contest270_5943.py
66 lines (49 loc) · 1.61 KB
/
contest270_5943.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
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# class Solution(object):
# def deleteMiddle(self, head):
# """
# :type head: Optional[ListNode]
# :rtype: Optional[ListNode]
# """
# head_backup = head
# middle = head
# pre_middle, post_middle = None, None
# if head.next:
# head = head.next
# middle = middle.next
# while True:
# post_middle = middle.next if middle.next else None
# pre_middle = middle
# middle = middle.next
# if pre_middle:
# pre_middle.next = post_middle
# if head.next is None:
# break
# if head.next.next is None:
# break
# head = head.next.next
# if pre_middle:
# pre_middle.next = post_middle
# return head_backup
class Solution(object):
def deleteMiddle(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
if head is None or head.next is None:
return None
end = head.next
pre_middle = head
while end.next and end.next.next:
end = end.next.next
pre_middle = pre_middle.next if pre_middle.next is not None else None
pre_middle.next = pre_middle.next.next
return head
if __name__ == '__main__':
sln = Solution()
output = sln.deleteMiddle()