Implementation of python double-ended queue

deque

A double-ended queue (deque, full name double-ended queue) is a data structure with the properties of a queue and a stack.

Elements in the deque can be popped from both ends, which restricts insertion and deletion to both ends of the table. Deques can be enqueued and dequeued at either end of the queue.


operate

  • Deque() creates an empty deque
  • add_front(item) adds an item element from the front of the queue
  • add_rear(item) adds an item element from the end of the queue
  • remove_front() removes an item element from the front of the queue
  • remove_rear() removes an item element from the end of the queue
  • is_empty() determines whether the double-ended queue is empty
  • size() returns the size of the queue

accomplish

class Dequeue(object):
    '''Double-ended queue, both ends can add or delete'''
    def __init__(self):
        self.__list = []

    def add_front(self, item):
        '''Add ''' to the header
        self.__list.insert(0, item)

    def add_rear(self, item):
        '''Add ''' at the end
        self.__list.append(item)

    def remove_front(self):
        '''Head delete'''
        return self.__list.pop(0)

    def remove_rear(self):
        '''Tail delete'''
        return self.__list.pop()

    def is_empty(self):
        '''Determine whether it is empty'''
        return self.__list == []

    def length(self):
        '''Get the length of the double-break queue'''
        return len(self.__list)


if __name__ == '__main__':
    dequeue = Dequeue()

    dequeue.add_front(1)
    dequeue.add_front(2)
    dequeue.add_front(3)

    dequeue.add_rear(4)
    dequeue.add_rear(5)

    print(dequeue._Dequeue__list)

    print(dequeue.remove_front())
    print(dequeue.remove_rear())

operation result:

/home/longhui/Desktop/Data Structures and Algorithms/venv/bin/python /home/longhui/Desktop/Data Structures and Algorithms/venv/MyCode/5_queue/my_dequeue.py
[3, 2, 1, 4, 5]
3
5

Process finished with exit code 0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325578088&siteId=291194637