Stack

Stack

Stack is a last-in-first-out (LIFO) data structure that restricts the way data is added or removed. Stacks are especially useful for implementing depth-first search.

A Stack inserts item to the end of the collection and also removes from the end. Both an array and a linked list would do this in O(1), but I've chosen linked list since there's no need for an array's random access capabilities in this context.

Constructor

new Stack()

Source:

Members

depth

Returns the number of items in the stack

Source:

Methods

peek() → {any}

Retrieve the item from the top of the stack

Source:

pop() → {any}

Remove element from the stack. Returns the removed value.

Runtime: O(1)

Source:

push(item) → {Stack}

Add element to the stack. Returns the Stack instance to allow the push() calls to be chained.

Runtime: O(1)

Parameters:
Name Type Description
item any
Source:
Example
stack.push(10)
   .push(20)
   .push(30)