DEV Community

Cover image for Stacks and Queues
Daniel Zaltsman
Daniel Zaltsman

Posted on • Edited on

Stacks and Queues

Stacks and queues are linear data structures that both contain objects and access them in a particular order. These structures use different principles to insert and remove their objects.

Stacks use the first-in-last-out(FILO)/last-in-first-out(LIFO) principle: The first object or item in a stack is the last object or item to leave the stack and the last item in a stack is the first to leave a stack.

Queues use first-in-first-out(FIFO)/last-in-last-out(LILO) principle: The first item in a stack is the first object or item to leave the stack, and the last item in a stack is the last to leave a stack.

Let's compare these two data structures in further detail.

Stacks

Alt Text

Elements can be inserted and deleted only from one side of the stack. A good way to look at stacks is to imagine it like a stack of books, where you can only remove from the top. When you add books, you're adding it to the top of the stack. When you insert an element into the stack, it's called push operation, and deletion of an element from a stack is called pop operation, both of which abide by the last-in-first-out principle(LIFO). We only need one pointer, which keeps track of the last element present in the list, called top.

Applications

-Reverse a word. You push a given word to stack - letter by letter - and then pop letters from the stack.
-"Undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack
-Backtracking. This is a process when you need to access the most recent data element in a series of elements.
-Language Processing. Using a stack, space for parameters and local variables is created internally, compiler's syntax check for matching braces is implemented, and support for recursion is available.

Queues

Alt Text

Queues work with both sides of the list. Elements can be inserted into one side, called rear, and on the the other side elements can be deleted from it called front. The methods for insertion and deletion are called enqueue and dequeue, respectively. Queues will always maintain two pointers, one pointing to the element which was inserted at the first position and still present in the list with the front pointer and the second position pointing to the element inserted at the last with the rear pointer.

Applications

-In operating systems, for controlling access to shared system resources such as printers, files, communication lines, disks and tapes
-When placed on hold for telephone operators.
-Handling of interrupts in real-time systems. The interrupts are handled in the same order as they arrive i.e First come first served.

Top comments (0)