-
Notifications
You must be signed in to change notification settings - Fork 411
Stack
In computer science, 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.[1] 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
var Stack = require('algorithms').DataStructure.Stack;
var s = new Stack();
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
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
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