Implementation of the queue
Like stacks, queues can also be implemented using sequential or linked lists.
operate
- Queue() creates an empty queue
- enqueue(item) adds an item element to the queue
- dequeue() removes an element from the head of the queue
- is_empty() determines whether a queue is empty
- size() returns the size of the queue
class Queue(object): '''Queue, first in first out''' def __init__(self): self.__list = [] def enqueue(self, item): '''Add elements from one end''' self.__list.append(item) def dequeue(self): '''Add element from the other end''' return self.__list.pop(0) def is_empty(self): '''Determine whether it is empty''' return self.__list == [] def length(self): '''Get the length of the queue''' return len(self.__list) if __name__ == '__main__': q = Queue() q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.length()) print(q.is_empty())
operation result:
/home/longhui/Desktop/Data Structures and Algorithms/venv/bin/python /home/longhui/Desktop/Data Structures and Algorithms/venv/MyCode/5_queue/my_queue.py 1 2 3 1 False Process finished with exit code 0