Lists, Stacks, and Queues

Lists


Stacks (ADT | Array-based implementation | Linked Stack)

Stack is a LIFO (Last-In, First-Out) list, a list-like structure in which elements may be inserted or removed from only one end (last-in, first-out). Stacks are less flexible than lists, but are easier to implement, and more efficient (for those operations they can do).
Given a stack, the accessible element of the stack is called the top element.
Elements are not said to be inserted; they are pushed onto the stack.
When an element (the last one) is removed, an element is said to be popped from the stack.
Both array-based and linked stacks are fairly easy to implement. Check out the two functions push() and pop() in the ADT of stacks & the different implementations (array-based and linked stacks). The cost for each push and pop operation is only $\Theta(1)$.

The implementation of subroutine calls (recursion) in most programming language runtime environments uses stacks: a subroutine call is implemented by placing necessary information about the subroutine (including the return address, parameters, and local variables) onto a stack. (see Figure 4.22 for an example of calculating factorials using recursion; see Example 4.2 for an interactive form of the factorial function using a stack).

Sample applications of stack:

Queues (ADT | Array-based implementation | Linked Queue

Queue is a FIFO (First-In, First-Out) list, a list-like structure that provides restricted access to its elements: elements may only be inserted at the back and removed from the front.
Similarly to stacks, queues are less flexible than lists.
Enqueue: insert elements into queue at the back.
Dequeue: remove elements from the front.
The linked queue implementation is a straightforward adaptation of the linked list. However, array-based queues might be tricky to implement. A naive implementation will require $\Theta(1)$ time for each enqueue operation, and $\Theta(n)$ for each dequeue operation (because all of the elements must be shifted down by one position to retain the property that the remaining $n-1$ queue elements reside in the first $n-1$ position of the array; the "drifting queue" problem). Using a "circular" queue can solve the problem.

What's available in Java