Implement a simple Queue class in Python
A queue is a first-in, first-out (FIFO) data structure. We can use Python lists to implement a simple queue class. This class will include the following basic operations:
enqueue(item): Add an element to the end of the queue.dequeue(): Remove and return the first element of the queue.is_empty(): Check whether the queue is empty.size(): Return the number of elements in the queue.
Example
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if self.is_empty():
return None
return self.items.pop(0)
def size(self):
return len(self.items)
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if self.is_empty():
return None
return self.items.pop(0)
def size(self):
return len(self.items)
Code analysis:
__init__The method initializes an empty listitems, used to store the elements in the queue.is_emptyThe method checks whether the queue is empty. Ifitemsthe list is empty, it returnsTrue; otherwise, it returnsFalse。enqueueThe method adds the elementitemto theitemsend of the list.dequeueThe method removes and returnsitemsthe first element of the list. If the queue is empty, it returnsNone。sizeThe method returnsitemsthe length of the list, i.e., the number of elements in the queue.
Output:
Example
# Example usage
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.dequeue()) # Output: 1
print(q.size()) # Output: 2
print(q.is_empty()) # Output: False
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.dequeue()) # Output: 1
print(q.size()) # Output: 2
print(q.is_empty()) # Output: False
In this example, we first create a queueq, then sequentially add the elements1、2and3to the queue. Next, we calldequeuemethod to remove and return the first element of the queue1. Finally, we check the size of the queue and whether it is empty, and output respectively2andFalse。
Python3 Examples