Skip to content

Instantly share code, notes, and snippets.

@sleebapaul
Created December 20, 2019 03:25
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 sleebapaul/3e2a686135cd75efdc9c017238f387e9 to your computer and use it in GitHub Desktop.
Save sleebapaul/3e2a686135cd75efdc9c017238f387e9 to your computer and use it in GitHub Desktop.
Implementation of Queue using Linked List
class Node(object):
"""
Fundamental building block of a linked list
A node consists of a value and the next node location pointer
"""
def __init__(self, value):
self.val = value
self.next = None
class MyQueue(object):
"""
Queue implementation using LinkedList
Queue works in FIFO manner
"""
def __init__(self):
self.head = None
self.tail = None
def enqueueItem(self, item):
"""
Add new item to queue - O(1)
Queuing always happens at tail
If Queuing happens at head, dequeuing will require in O(n)
"""
newNode = Node(item)
if self.tail:
self.tail.next = newNode
self.tail = self.tail.next
else:
self.tail = newNode
self.head = self.tail
def dequeueItem(self):
"""
Dequeue item from queue - O(1)
"""
try:
self.head = self.head.next
except AttributeError as error:
self.head = None
def peekQueue(self):
"""
Peek the top value of the queue - O(1)
"""
try:
return self.head.val
except AttributeError as error:
return None
def isEmpty(self):
return self.head == self.tail
# if __name__ == "__main__":
# myQueue = MyQueue()
# print("Peek QValue", myQueue.peekQueue())
# myQueue.enqueueItem(9)
# print("Peek QValue", myQueue.peekQueue())
# myQueue.enqueueItem(10)
# print("Peek QValue", myQueue.peekQueue())
# myQueue.dequeueItem()
# print("Peek QValue", myQueue.peekQueue())
# myQueue.dequeueItem()
# print("Peek QValue", myQueue.peekQueue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment