Skip to content

Instantly share code, notes, and snippets.

@TheAlchemistKE
Created June 6, 2023 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheAlchemistKE/cb8271e6e87d7534ea5b281eb3d39737 to your computer and use it in GitHub Desktop.
Save TheAlchemistKE/cb8271e6e87d7534ea5b281eb3d39737 to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
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
else:
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
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def delete_at_head(self):
if self.is_empty():
print("Linked list is empty. No node to delete.")
else:
self.head = self.head.next
def delete_at_tail(self):
if self.is_empty():
print("Linked list is empty. No node to delete.")
elif self.head.next is None:
self.head = None
else:
current = self.head
while current.next.next:
current = current.next
current.next = None
def display(self):
if self.is_empty():
print("Linked list is empty.")
else:
current = self.head
while current:
print(current.data, end=" ")
current = current.next
print()
# Usage example:
linked_list = SinglyLinkedList()
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_at_head()
linked_list.delete_at_tail()
linked_list.display() # Output: 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment