Skip to content
Felipe Ribeiro edited this page Feb 19, 2014 · 4 revisions

Definition

A stack is a particular kind of abstract data type or collection in which the principal (or only) operations on the collection are the addition of an entity to the collection, known as push and removal of an entity, known as pop. The relation between the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure. In a LIFO data structure, the last element added to the structure must be the first one to be removed. This is equivalent to the requirement that, considered as a linear data structure, or more abstractly a sequential collection, the push and pop operations occur only at one end of the structure, referred to as the topof the stack. Often a peek or top operation is also implemented, returning the value of the top element without removing it.

Source: Wikipedia

Code: https://github.com/felipernb/algorithms.js/blob/master/data_structures/stack.js

Test: https://github.com/felipernb/algorithms.js/blob/master/test/data_structures/stack.js

How to use

Import

var Stack = require('algorithms').DataStructure.Stack;

Initialization

var s = new Stack();

Stack.prototype.push(e)

Pushes an element to the top of the Stack (O(1))

var s = new Stack();
s.push(1); // (1)<top
s.push(2); // (1)(2)<top
s.push(3); // (1)(2)(3)<top

Stack.prototype.pop()

Pops an element from the top of the Stack (O(1))

var 2 = new Stack();
s.push(1); // (1)<top
s.push(2); // (1)(2)<top
s.push(3); // (1)(2)(3)<top
s.pop(); // 3
s.pop(); // 2
s.pop(); //1

Stack.prototype.peek()

Returns the element from the top of the Stack, without removing it (O(1))

var q = new Stack();
s.push(1); // (1)<top
s.push(2); // (1)(2)<top
s.push(3); // (1)(2)(3)<top
s.peek(); // 3
s.peek(); // 3
s.pop(); // 3
s.peek(); // 2
Clone this wiki locally