Created
June 6, 2023 18:18
-
-
Save cod3smith/53fe1666bd7a8566dc957b116bb3d981 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.prev = None | |
self.next = None | |
class DoublyLinkedList: | |
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.prev = new_node | |
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 | |
new_node.prev = current | |
def delete_at_head(self): | |
if self.is_empty(): | |
print("Linked list is empty. No node to delete.") | |
else: | |
if self.head.next is None: | |
self.head = None | |
else: | |
self.head = self.head.next | |
self.head.prev = None | |
def delete_at_tail(self): | |
if self.is_empty(): | |
print("Linked list is empty. No node to delete.") | |
else: | |
if self.head.next is None: | |
self.head = None | |
else: | |
current = self.head | |
while current.next: | |
current = current.next | |
current.prev.next = None | |
def display_forward(self): | |
if self.is_empty(): | |
print("Linked list is empty.") | |
else: | |
current = self.head | |
while current: | |
print(current.data, end=" ") | |
current = current.next | |
print() | |
def display_backward(self): | |
if self.is_empty(): | |
print("Linked list is empty.") | |
else: | |
current = self.head | |
while current.next: | |
current = current.next | |
while current: | |
print(current.data, end=" ") | |
current = current.prev | |
print() | |
# Usage example: | |
linked_list = DoublyLinkedList() | |
linked_list.insert_at_head(5) | |
linked_list.insert_at_head(3) | |
linked_list.insert_at_tail(7) | |
linked_list.display_forward() # Output: 3 5 7 | |
linked_list.display_backward() # Output: 7 5 3 | |
linked_list.delete_at_head() | |
linked_list.delete_at_tail() | |
linked_list.display_forward() # Output: 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment