-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeleteMiddle.py
40 lines (32 loc) · 1.35 KB
/
deleteMiddle.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
# You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.
# The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.
# For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.
# Example 1:
# [1]
# Input: head = [1,3,4,7,1,2,6]
# Output: [1,3,4,1,2,6]
# Explanation:
# The above figure represents the given linked list. The indices of the nodes are written below.
# Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
# We return the new list after removing this node.
# 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]
"""
if head.next == None:
return None
last, current = head, head
currentDouble = head
while currentDouble != None and currentDouble.next != None:
currentDouble = currentDouble.next.next
last = current
current = current.next
last.next = current.next
return head