-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeleteMiddle.py
49 lines (40 loc) · 1.34 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
41
42
43
44
45
46
47
48
49
# Definition for singly-linked list.
class Node:
def __init__(self, val):
self.val = val
self.next = next
class LinkedList:
def deleteMiddle(self, head):
#initialize
slowP = head
fastP = head.next
while fastP.next != None and fastP.next.next != None:
#now move it along....takes a while
#to understand this logic
fastP = fastP.next.next
slowP = slowP.next
#below logic: slowP has val 2 so slowP.next has val
#3(one to be deleted. by assigning slowP.next.next
#to slowP.next we are deleting the link bet 2 and 3
#twisted code !!!!!!!!!!!!!!!!!! we are not deleting it
#we just broke the link
slowP.next = slowP.next.next
print(slowP.next)
print(slowP.next.next.val)
return head
#racking my brains with the driver code
#no need to do so...since I already
#have the LL already define so I can pass
#"head" to the method oddEvenList
llist = LinkedList()
llist.head = Node(1)
secondN = Node(2)
thirdN = Node(3)
fourthN = Node(4)
fifthN = Node(5)
llist.head.next = secondN
secondN.next = thirdN
thirdN.next = fourthN
fourthN.next = fifthN
fifthN.next = None
llist.deleteMiddle(llist.head)