Created
August 8, 2020 10:52
-
-
Save cs-fedy/fda66d6e3d271bd8a61076d8d89edcda to your computer and use it in GitHub Desktop.
Implementing doubly linked-list in Python programming language.
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, key): | |
self.key = key | |
self.next = None | |
self.prev = None | |
class DoublyLinkedList: | |
def __init__(self): | |
self.head = None | |
# traverse | |
def __repr__(self): | |
return " <--> ".join(str(node.key) for node in self) | |
def __iter__(self): | |
node = self.head | |
while node is not None: | |
yield node | |
node = node.next | |
def is_empty(self): | |
return not self.head | |
# insert | |
def insert_first(self, key): | |
new_node = Node(key) | |
new_node.next = self.head | |
self.head = new_node | |
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.prev = curr_node | |
curr_node.next = new_node | |
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: | |
new_node.next = curr_node.next | |
new_node.prev = curr_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: | |
new_node = Node(key) | |
new_node.next = curr_node | |
new_node.prev = prev_node | |
prev_node.next = new_node | |
return | |
prev_node = curr_node | |
raise Exception(f"key = {target_key} doesn't exist in the list") | |
# remove | |
def remove(self, key): | |
if self.is_empty(): | |
raise Exception("List is Empty!!") | |
if self.head.key == key: | |
self.head = self.head.next | |
self.head.prev = None | |
return | |
prev_node = self.head | |
for curr_node in self: | |
if curr_node.key == key: | |
temp_node = curr_node.next | |
temp_node.prev = prev_node | |
prev_node.next = temp_node | |
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