![]() ![]() As with many things, it is up to you what you want to achieve, and a double-ended queue is just another tool in your toolkit to consider. ![]() The official documentation is the first place to go, and you can also check out a Real Python article on the subject. We have explored a very simple way to create stacks and queues using a deque, but of course, there is a lot more to dive into. Nothing much seems different, but you can also imagine using the other end, using appendleft() together with popleft() as well. pop () def peek ( self ): """Get the value of the top item in the stack.""" return self. append ( item ) def pop ( self ): """Remove an item from the stack.""" return self. _items ) def push ( self, item ): """Add an item to the stack.""" self. _items = deque () def is_empty ( self ): """Check if the stack is empty.""" return not bool ( self. Using a list, you might have seen a stack as implemented as such*:įrom collections import deque class Stack : """Stack implementation as a deque.""" def _init_ ( self ): """Create new stack.""" self. This is also another reason why a deque is great - you can imagine that we can also use a Python list for the same goal, but in that case, if we want to insert and remove from the beginning (say, from the left end), the operation will take O(n) time, which is, well, not so good. Implemented as a doubly-linked list under the hood, insertion and deletion operations will take O(1), constant time. With a “double-ended queue”, or a deque-pronounced as “deck”-, we can enqueue or dequeue, or, push and pop items from both ends at any time. With a queue, the first item inserted is going to be removed first, similar to a queue in real life, so, enqueue and dequeue operations are done from the opposite ends of the queue. With a stack, the last item inserted is the first to go out, so, we push and pop from one end of the stack. One important aspect is that each of them has different principles when it comes to their behavior when inserting and removing elements - LIFO (last in, first out) for stacks, FIFO (first in, first out) for queues. Two of the abstract data types that you are most likely to have encountered before are stacks and queues. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |