forked from dsrao711/DSA-Together-HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
circular_linked_list_insertion_at_pos.py
82 lines (74 loc) · 1.98 KB
/
circular_linked_list_insertion_at_pos.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
78
79
80
81
82
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
#Add new element at the end of the list
def InsertAtEnd(self, newElement):
newNode = Node(newElement)
if(self.head == None):
self.head = newNode
newNode.next = self.head
return
else:
temp = self.head
while(temp.next != self.head):
temp = temp.next
temp.next = newNode
newNode.next = self.head
#Inserts a new element at the given position
def InsertAtPos(self, newElement, position):
newNode = Node(newElement)
temp = self.head
NoOfElements = 0
if(temp != None):
NoOfElements += 1
temp = temp.next
while(temp != self.head):
NoOfElements += 1
temp = temp.next
if(position < 1 or position > (NoOfElements+1)):
print("\nInavalid position.")
elif (position == 1):
if(self.head == None):
self.head = newNode
self.head.next = self.head
else:
while(temp.next != self.head):
temp = temp.next
newNode.next = self.head
self.head = newNode
temp.next = self.head
else:
temp = self.head
for i in range(1, position-1):
temp = temp.next
newNode.next = temp.next
temp.next = newNode
#display the content of the list
def PrintList(self):
temp = self.head
if(temp != None):
print("The list contains:", end=" ")
while (True):
print(temp.data, end=" ")
temp = temp.next
if(temp == self.head):
break
else:
print("The list is empty.")
# test the code
MyList = LinkedList()
#Add three elements at the end of the list.
MyList.InsertAtEnd(10)
MyList.InsertAtEnd(20)
MyList.InsertAtEnd(30)
MyList.PrintList()
#Insert an element at position 2
MyList.InsertAtPos(100, 2)
MyList.PrintList()
#Insert an element at position 1
MyList.InsertAtPos(200, 1)
MyList.PrintList()