Stack



 is a linear data structure for storing and retrieving data. It basically follows the LIFO rule (last-in-first-out).

The two common operations to modify a stack are:
 * Push: to insert an element at the top of the stack.
 * Pop: to remove an element from the top of the stack.

Moving stacks

 * When you move all elements one-by-one from Stack 1 into Stack 2, the elements are reversed in Stack 2.
 * When you move all elements from Stack 1 to Stack 2, and move part of or all of elements back to Stack 1, then the elements moved back to Stack 1 are kept in its original order. The amortized time complexity for each move operation can often be programmed to be O(1).

Common usages

 * When you linearly scan an array from left to right, and need to continuously look at elements on the left, Stack is often needed.

Sample problems

 * Sort with two stacks
 * Min stack
 * Repeatedly deduplication
 * Reversed Polish Notation (Example: )
 * Largest rectangle in a histogram

C++

 * cplusplus.com: std::stack
 * cppreference.com:, std::stack

Java

 * interface
 * class

Python

 * collections.deque