DEV Community

ivinieon
ivinieon

Posted on

Concepts and Use Cases of Stack and Queue

1. Concepts and Use Cases of Stack and Queue

2. Tips When Encountering a Queue in Technical Documents

3. Troubleshooting Errors Related to Stack and Queue

Abstract Data Type (ADT)

  • Defines only what operations should be performed without specifying how they should be implemented
  • Does not cover implementation details

Data structure (DS)

  • A concrete implementation of the ADT
  • Implements the operations defined in the ADT

Stack and Queue from the perspective of ADT

Stack: A structure that stores data in Last In First Out (LIFO) order

  • push: Adds an item to the stack
  • pop: Removes an item from the stack
  • peek: Retrieves the value of the topmost item in the stack

Since the item that is inserted first is placed at the bottom of the stack, the item that is inserted last is the first to be removed.

Queue: A structure that stores data in First In First Out (FIFO) order

  • enqueue: Adds an item to the queue
  • dequeue: Removes an item from the queue
  • peek: Retrieves the value of the frontmost item in the queue

The item that is inserted first is the first to be removed.

Use Cases for Stack: Stack Memory and Stack Frame

python
Copy code
def a():
        b()
def b():
        c()
def c():
        print("wow")
Enter fullscreen mode Exit fullscreen mode

When a() is called, a stack for a() is created in the stack memory. Since b() is called inside a(), a stack for b() is also created. Similarly, when b() is called, a stack for c() is created. After the "wow" is printed, c() is removed from the stack, followed by b(), and finally a().

Use Cases for Queue: Producer/Consumer Architecture

The producer creates and the consumer consumes.

Tips When Encountering a Queue in Technical Documents

FIFO is not always implied: In a priority queue, items with higher priority are removed first.

Stack/Queue Related Errors and Troubleshooting Methods

StackOverflowError
An error that occurs when the stack memory is exhausted. This error occurs when a recursive function cannot exit.

Recursive Function: Calling a function within itself.

python
Copy code
def recur_fibo(n):
    if n<=1:
        return n
    else:
        return(Recur_fino(n-1)+recur_fibo(n-2))
Enter fullscreen mode Exit fullscreen mode

OutOfMemoryError
An error that occurs when the Java heap memory is exhausted. This error occurs when the queue is constantly being filled with data.

Heap: The area where objects reside.

The queue size should be fixed. What if the queue is full?

  • Throw an exception
  • Return a special value (null or false)
  • Block the thread indefinitely until success
  • Block the thread for a limited amount of time and then give up

LinkedBlockingQueue

Image description

This posting is just a study note which was written after watching youtube videos in Korean.
Youtube

Top comments (0)