Skip to content

circular_linked_list.py #873

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions data_structures/linked_list/circular_linked_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from __future__ import print_function

class Node: #create a node
def __init__(self,data):
self.data = data #giving data
self.next = None #giving next to None

class Circular_Linked_List:
def __init__(self):
self.last = None #Initializing last to None

def insert_beginning(self,data):
newNode = Node(data) #create node
if self.last == None: #If last is None, Make newNode last
self.last = newNode
self.last.next = self.last
else:
newNode.next = self.last.next #set newnode's next as head
self.last.next = newNode

def insert_end(self,data):
newNode = Node(data)
if self.last == None:
self.last = newNode
self.last.next = self.last
else:
newNode.next = self.last.next #set newnode's next as head
self.last.next = newNode
self.last = newNode #set newnode as last node

def delete_beginning(self):
node = self.last.next
self.last.next = node.next #set last's next to first node's next
return node.data

def delete_end(self):
temp = self.last.next
while temp.next is not self.last: #Traversing the list
temp=temp.next
node = self.last
temp.next = self.last.next #set second last node's next to last's next
self.last = temp
return node.data

def print_list(self):
print("The list is:")
temp = self.last.next #Creating iterator
while temp is not self.last: #Traversing the list
print(temp.data)
temp = temp.next
print(temp.data) #print last node

#End Class

def main():
LL = Circular_Linked_List()
print("Inserting at beginning: ")
a1 = input()
LL.insert_beginning(a1)
print("Inserting at beginning: ")
a2 = input()
LL.insert_beginning(a2)
LL.print_list()
print("Inserting at the end: ")
a1 = input()
LL.insert_end(a1)
print("Inserting at the end: ")
a2 = input()
LL.insert_end(a2)
LL.print_list()
print("Deleting from beginning")
print(LL.delete_beginning()," deleted")
LL.print_list()
print("Deleting from end")
print(LL.delete_end()," deleted")
LL.print_list()

if __name__ == '__main__':
main()