DEV Community

loading...

Day 38 Of 100DaysOfCode : Basic Data Structure, Queue

iamdurga profile image Durga Pokharel ・3 min read

This is my 38th day of 100 Days of code and python like as yesterday
I revised older exercise. And learned few concept of data structure from coursera. Also I learned about basic of next one data structure i.e, queue. While learning I thought that it was like queue in a gas line. In which we take first element and left out first element earlier. Queue is used in solving problems having sequential processing.

Few Concept About Queue Are

  • Queue operates in FIFO(first in first out)
  • Queue has dynamic and fixed size
  • The insertation in list is called an enqueue operation
  • The delection in the list is called a deletion operation.
  • We maintain two pointer(one frnot pointer and next rear pointer)

Python Code

class Queue:

    def __init__(self):
        self.queue = []
        print(f"Queue Initialized as {self.queue}")

    # Add an element
    def enqueue(self, item):
        self.queue.append(item)
        print(f"{item} added into the queue. Updated Queue is {self.queue}.")

    # Remove an element
    def dequeue(self):
        if len(self.queue) < 1:
            print("Queue is empty. Nothing to remove.")
            return None
        p=self.queue.pop(0)
        print(f"{p} is removed. Updated Queue is {self.queue}.")
        return p

    # Display  the queue
    def display(self):
        print(f"Current Queue: {self.queue}")



q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.enqueue(6)


q.display()

q.dequeue()
q.dequeue()
q.dequeue()
q.dequeue()
q.dequeue()


print(f"After removing an element")
q.display()
Enter fullscreen mode Exit fullscreen mode

When this code is run we get following output.

Queue Initialized as []
1 added into the queue. Updated Queue is [1].
2 added into the queue. Updated Queue is [1, 2].
3 added into the queue. Updated Queue is [1, 2, 3].
4 added into the queue. Updated Queue is [1, 2, 3, 4].
5 added into the queue. Updated Queue is [1, 2, 3, 4, 5].
6 added into the queue. Updated Queue is [1, 2, 3, 4, 5, 6].
Current Queue: [1, 2, 3, 4, 5, 6]
1 is removed. Updated Queue is [2, 3, 4, 5, 6].
2 is removed. Updated Queue is [3, 4, 5, 6].
3 is removed. Updated Queue is [4, 5, 6].
4 is removed. Updated Queue is [5, 6].
5 is removed. Updated Queue is [6].
After removing an element
Current Queue: [6]

Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide