-
Notifications
You must be signed in to change notification settings - Fork 82
/
circularLinkedListTraversal.py
61 lines (46 loc) · 1.21 KB
/
circularLinkedListTraversal.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
# Python program to demonstrate
# circular linked list traversal
# Structure for a Node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
# Constructor to create a empty circular linked list
def __init__(self):
self.head = None
# Function to insert a node at the beginning of a
# circular linked list
def push(self, data):
ptr1 = Node(data)
temp = self.head
ptr1.next = self.head
# If linked list is not None then set the next of
# last node
if self.head is not None:
while(temp.next != self.head):
temp = temp.next
temp.next = ptr1
else:
ptr1.next = ptr1 # For the first node
self.head = ptr1
# Function to print nodes in a given circular linked list
def printList(self):
temp = self.head
if self.head is not None:
while(True):
print (temp.data, end=" ")
temp = temp.next
if (temp == self.head):
break
# Driver program to test above function
# Initialize list as empty
cllist = CircularLinkedList()
# Created linked list will be 11->2->56->12
cllist.push(12)
cllist.push(56)
cllist.push(2)
cllist.push(11)
print ("Contents of circular Linked List")
cllist.printList()