Categories: Data Structurepython

Implementation of Queue in Python

Overview of Queue Data Structure πŸ€”πŸ€“

  • AΒ queueΒ is an ordered collection of items where the addition of new items happens at one end, called the β€œrear,” and the removal of existing items occurs at the other end, commonly called the β€œfront.”
  • As an element enters the queue it starts at the rear and makes its way toward the front, waiting until that time when it is the next element to be removed.
  • The most recently added item in the queue must wait at the end of the collection. Β¨The item that has been in the collection the longest is at the front.
  • This ordering principle is sometimes called FIFO, first-in-first-out. πŸ‘ˆπŸ˜²
  • It is also known as β€œfirst-come-first-served.” πŸ‘ˆπŸ˜
  • The simplest example of a queue is the typical line that we all participate in from time to time.
  • We wait in a line for a movie, we wait in the check-out line at a grocery store, and we wait in the cafeteria line.
  • The first person in that line is also the first person to get serviced/helped.
  • Note how we have two terms here, Enqueue and Dequeue. πŸ€—βœŒοΈ
  • The enqueue term describes when we add a new item to the rear of the queue.
  • The dequeue term describes removing the front item from the queue.
  • You should now have a basic understanding of Queues and the FIFO principal for them. πŸ‘ŒπŸ‘Œ

Now we are going to implement our own Queue class πŸ‘‡πŸ‘‡

class Queue(object):

 def __init__(self):

  self.items = []

 def  isEmpty(self):
  
  return self.items == []

 def enqueue(self, data):

  return self.items.insert(0, data)

 def dequeue(self):

  return self.items.pop()

 def size(self):

  return len(self.items)

q = Queue()

print("Is Empty {}".format(q.isEmpty()))

q.enqueue(1)
q.enqueue(2)
q.enqueue(3)

print(q.dequeue())
print("Size {}".format(q.size()))

Recommended Reading:

How to start learning Python Programming πŸ‘ˆ

Implementation of Stack in Python πŸ‘ˆ

Follow Me ❀😊

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Recent Posts

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago