Created
June 6, 2023 18:22
-
-
Save TheAlchemistKE/fa152317732325aef1c2249188496073 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, data): | |
self.data = data | |
self.next = None | |
class CircularLinkedList: | |
def __init__(self): | |
self.head = None | |
def is_empty(self): | |
return self.head is None | |
def insert_at_head(self, data): | |
new_node = Node(data) | |
if self.is_empty(): | |
self.head = new_node | |
new_node.next = self.head | |
else: | |
current = self.head | |
while current.next != self.head: | |
current = current.next | |
current.next = new_node | |
new_node.next = self.head | |
self.head = new_node | |
def insert_at_tail(self, data): | |
new_node = Node(data) | |
if self.is_empty(): | |
self.head = new_node | |
new_node.next = self.head | |
else: | |
current = self.head | |
while current.next != self.head: | |
current = current.next | |
current.next = new_node | |
new_node.next = self.head | |
def delete(self, data): | |
if self.is_empty(): | |
print("Linked list is empty. No node to delete.") | |
elif self.head.data == data: | |
current = self.head | |
while current.next != self.head: | |
current = current.next | |
current.next = self.head.next | |
self.head = self.head.next | |
else: | |
current = self.head | |
prev = None | |
while current.next != self.head: | |
if current.data == data: | |
prev.next = current.next | |
return | |
prev = current | |
current = current.next | |
if current.data == data: | |
prev.next = self.head | |
def display(self): | |
if self.is_empty(): | |
print("Linked list is empty.") | |
else: | |
current = self.head | |
while True: | |
print(current.data, end=" ") | |
current = current.next | |
if current == self.head: | |
break | |
print() | |
# Usage example: | |
linked_list = CircularLinkedList() | |
linked_list.insert_at_head(5) | |
linked_list.insert_at_head(3) | |
linked_list.insert_at_tail(7) | |
linked_list.display() # Output: 3 5 7 | |
linked_list.delete(3) | |
linked_list.display() # Output: 5 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment