Queue Operations
In this section, we will discuss the operations associated with queues: enqueue, dequeue, and peek.
Enqueue Operation
The enqueue operation adds an element to the end of the queue. It increases the size of the queue by one and places the new element at the rear.
In the implementation of a queue, the enqueue operation can be performed by using the append
method in Python to add the element to the rear of the list.
Here is an example of how the enqueue operation works in Python:
1queue = []
2queue.append(1)
3queue.append(2)
4queue.append(3)
5
6print(queue) # Output: [1, 2, 3]
Dequeue Operation
The dequeue operation removes the element from the front of the queue and returns it. It decreases the size of the queue by one.
In the implementation of a queue, the dequeue operation can be performed by using the pop
method with an index of 0 to remove and return the front element of the list.
Here is an example of how the dequeue operation works in Python:
1queue = [1, 2, 3]
2
3print(queue.pop(0)) # Output: 1
4print(queue) # Output: [2, 3]
Peek Operation
The peek operation returns the front element of the queue without modifying the queue. It does not change the size of the queue.
In the implementation of a queue, the peek operation can be performed by accessing the element at index 0 in the list.
Here is an example of how the peek operation works in Python:
1queue = [1, 2, 3]
2
3print(queue[0]) # Output: 1
4print(queue) # Output: [1, 2, 3]
It is important to note that performing the dequeue or peek operation on an empty queue will result in an error.
Now that we have a good understanding of the queue operations, we can move on to the next section where we will learn about stack applications in robotics and computer vision.
xxxxxxxxxx
print("Front of queue:", peek(queue))
if __name__ == "__main__":
# Create an empty queue
def create_queue():
queue = []
return queue
# Function to add an item to the queue
def enqueue(queue, item):
queue.append(item)
print("Enqueued item:", item)
# Function to remove an item from the queue
def dequeue(queue):
if len(queue) < 1:
return None
return queue.pop(0)
# Function to get the front item in the queue
def peek(queue):
if len(queue) < 1:
return None
return queue[0]
# Main function
if __name__ == "__main__":
queue = create_queue()
enqueue(queue, 1)
enqueue(queue, 2)
enqueue(queue, 3)