mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
reorganize dir
Signed-off-by: Mia Steinkirch <mia.steinkirch@gmail.com>
This commit is contained in:
parent
1b6f705e7c
commit
a8e71c50db
276 changed files with 23954 additions and 0 deletions
80
ebook_src/abstract_structures/queues/linked_queue.py
Normal file
80
ebook_src/abstract_structures/queues/linked_queue.py
Normal file
|
@ -0,0 +1,80 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' Queue acts as a container for nodes (objects) that are inserted and removed according FIFO'''
|
||||
|
||||
|
||||
class Node(object):
|
||||
def __init__(self, value=None, pointer=None):
|
||||
self.value = value
|
||||
self.pointer = None
|
||||
|
||||
|
||||
class LinkedQueue(object):
|
||||
def __init__(self):
|
||||
self.head = None
|
||||
self.tail = None
|
||||
|
||||
|
||||
def isEmpty(self):
|
||||
return not bool(self.head)
|
||||
|
||||
|
||||
def dequeue(self):
|
||||
if self.head:
|
||||
value = self.head.value
|
||||
self.head = self.head.pointer
|
||||
return value
|
||||
else:
|
||||
print('Queue is empty, cannot dequeue.')
|
||||
|
||||
|
||||
def enqueue(self, value):
|
||||
node = Node(value)
|
||||
if not self.head:
|
||||
self.head = node
|
||||
self.tail = node
|
||||
else:
|
||||
if self.tail:
|
||||
self.tail.pointer = node
|
||||
self.tail = node
|
||||
|
||||
|
||||
def size(self):
|
||||
node = self.head
|
||||
num_nodes = 0
|
||||
while node:
|
||||
num_nodes += 1
|
||||
node = node.pointer
|
||||
return num_nodes
|
||||
|
||||
|
||||
def peek(self):
|
||||
return self.head.value
|
||||
|
||||
|
||||
def _print(self):
|
||||
node = self.head
|
||||
while node:
|
||||
print(node.value)
|
||||
node = node.pointer
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
queue = LinkedQueue()
|
||||
print("Is the queue empty? ", queue.isEmpty())
|
||||
print("Adding 0 to 10 in the queue...")
|
||||
for i in range(10):
|
||||
queue.enqueue(i)
|
||||
print("Is the queue empty? ", queue.isEmpty())
|
||||
queue._print()
|
||||
|
||||
print("Queue size: ", queue.size())
|
||||
print("Queue peek : ", queue.peek())
|
||||
print("Dequeue...", queue.dequeue())
|
||||
print("Queue peek: ", queue.peek())
|
||||
queue._print()
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue