From 6fbcd9fe4fff6d732f618b78255ad28d281cb40e Mon Sep 17 00:00:00 2001 From: Vishesh-dd4723 Date: Fri, 1 Oct 2021 15:37:31 +0530 Subject: [PATCH] Added data structure --- .../linked-lists/doubly linked list.py | 52 +++++++++++++++++++ algorithms/data-structures/queue/queue.py | 43 +++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 algorithms/data-structures/linked-lists/doubly linked list.py create mode 100644 algorithms/data-structures/queue/queue.py diff --git a/algorithms/data-structures/linked-lists/doubly linked list.py b/algorithms/data-structures/linked-lists/doubly linked list.py new file mode 100644 index 0000000..e88f14d --- /dev/null +++ b/algorithms/data-structures/linked-lists/doubly linked list.py @@ -0,0 +1,52 @@ +class Node: + def __init__(self, value): + self.value = value + self.next = None + self.prev = None + +class DoublyLinkedList: + def __init__(self, object): + self.tail = self.head = Node(object) + + def append(self, object): + c = self.tail + self.tail.next = Node(object) + self.tail = self.tail.next + self.tail.prev = c + + def insert(self, index, object): + new_node = Node(object) + if index == 0: + ll = new_node + self.head.prev = ll + ll.next = self.head + self.head = ll + else: + current_indx = 0 + ll = self.head + while current_indx < index - 1: + ll = ll.next + current_indx += 1 + ll.next.prev = new_node + new_node.next = ll.next + ll.next = new_node + new_node.prev = ll + + def pop(self): + curr = self.head + while curr.next.next != None: + curr = curr.next + self.tail = curr + self.tail.next = None + + def show(self, reverse = False): + if reverse: + curr = self.tail + while curr: + print(curr.value) + curr = curr.prev + else: + curr = self.head + while curr: + print(curr.value) + curr = curr.next diff --git a/algorithms/data-structures/queue/queue.py b/algorithms/data-structures/queue/queue.py new file mode 100644 index 0000000..262b225 --- /dev/null +++ b/algorithms/data-structures/queue/queue.py @@ -0,0 +1,43 @@ +class Node(): + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + +class Queue(): + def __init__(self): + self.tail = self.head = None + self.length = 0 + + def insert(self, object): + if self.length == 0: + self.tail = self.head = Node(object) + else: + c = Node(object) + self.head.prev = c + c.next = self.head + self.head = c + self.length += 1 + + def pop(self): + if self.length == 1: + value = self.tail.data + self.tail = self.head = None + else: + c = self.tail.prev + value = self.tail.data + c.next = None + self.tail = c + self.length -= 1 + return value + + def isEmpty(self): + return not bool(self.length) + + def show(self): + curr = self.head + lst = [] + while curr: + lst.append(curr.data) + curr = curr.next + return lst \ No newline at end of file