Stack

November 28, 2023 · View on GitHub

Introduction

A stack is an abstract data type that supports the operations push (insert a new element on the top of the stack) and pop (remove and return the most recently added element, the element at the top of the stack). As an abstract data type, stacks can be implemented using arrays or singly linked lists.

This behavior is commonly called LIFO (last in, first out). The name "stack" for this type of structure comes from the analogy to a set of physical items stacked on top of each other.

Stacks are an important way of supporting nested or recursive function calls and is used to implement depth-first search. Depth-first search can be implemented using recursion or a manual stack.

Learning resources

Implementations

LanguageAPI
C++std::stack
Javajava.util.Stack
PythonSimulated using List
JavaScriptSimulated using Array

Time complexity

OperationBig-O
Top/PeekO(1)
PushO(1)
PopO(1)
isEmptyO(1)
SearchO(n)

Corner cases

  • Empty stack. Popping from an empty stack
  • Stack with one item
  • Stack with two items

Essential questions

These are essential questions to practice if you're studying for this topic.

These are recommended questions to practice after you have studied for the topic and have practiced the essential questions.