-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find_the_middle_element.py
52 lines (39 loc) · 1.23 KB
/
Find_the_middle_element.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
class Node:
def __init__(self, value):
self.data = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.n = 0
def __len__(self):
return self.n
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
self.n = self.n + 1
def printList(self):
curr = self.head
while curr != None:
print(str(curr.data)+"->", end='')
curr = curr.next
print('NULL')
def middle(self):
# Find out the length of index and do floor division to find middle index value
a = (len(llist))//2
pos = 0 # Creat an initial pointer
curr = self.head
while curr != None:
if pos == a: # Run the loop until the middle index value matches the pointer
# Once they match, return the data in the particular index value
print(curr.data)
curr = curr.next
pos = pos + 1
if __name__ == '__main__':
# Start with the empty list
llist = LinkedList()
for i in range(5, 0, -1):
llist.push(i)
llist.printList()
llist.middle()