Skip to content

Instantly share code, notes, and snippets.

@cs-fedy
Last active August 8, 2020 10:53
Show Gist options
  • Select an option

  • Save cs-fedy/75aa8412b138fa1f7a74b5251cc78409 to your computer and use it in GitHub Desktop.

Select an option

Save cs-fedy/75aa8412b138fa1f7a74b5251cc78409 to your computer and use it in GitHub Desktop.
Implementing circular linked-list in Python programming language.
class Node:
def __init__(self, key):
self.key = key
self.next = None
self.prev = None
class CircularLinkedList:
def __init__(self):
self.head = None
# traverse
def get_list(self, starting_point=None):
return " -> ".join(str(node.key) for node in self.__iter__(starting_point))
def __iter__(self, starting_point=None):
if not starting_point:
starting_point = self.head
curr_node = starting_point
while curr_node.next != starting_point:
yield curr_node
curr_node = curr_node.next
yield curr_node
def is_empty(self):
return not self.head
# insert
def insert_first(self, key):
new_node = Node(key)
if self.is_empty():
self.head = new_node
new_node.next = new_node
else:
for curr_node in self: pass
new_node.next = self.head
self.head = new_node
curr_node.next = self.head
def insert_after(self, target_key, key):
if self.is_empty():
raise Exception("List is Empty!!")
new_node = Node(key)
for curr_node in self:
if curr_node.key == target_key:
temp_node = curr_node.next
new_node.next = temp_node
curr_node.next = new_node
return
raise Exception(f"key = {target_key} doesn't exist in the list")
def insert_before(self, target_key, key):
if self.is_empty():
raise Exception("List is Empty!!")
if self.head.key == target_key:
return self.insert_first(key)
prev_node = self.head
for curr_node in self:
if curr_node.key == target_key:
temp_node = Node(key)
temp_node.next = curr_node
prev_node.next = temp_node
return
prev_node = curr_node
raise Exception(f"key = {target_key} doesn't exist in the list")
def insert_last(self, key):
if self.is_empty():
return self.insert_first(key)
for curr_node in self: pass
new_node = Node(key)
new_node.next = curr_node.next
curr_node.next = new_node
# remove
def remove(self, key):
if self.is_empty():
raise Exception("List is Empty!!")
if self.head.key == key:
for curr_node in self: pass
self.head = self.head.next
curr_node.next = self.head
return
prev_node = self.head
for curr_node in self:
if curr_node.key == key:
prev_node.next = curr_node.next
return
prev_node = curr_node
raise Exception(f"key = {key} doesn't exist in the list")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment