forked from AllAlgorithms/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
72 lines (67 loc) · 1.4 KB
/
stack.js
File metadata and controls
72 lines (67 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* @author Rashik Ansar
*
* Implemtaion of Stack data structure
* Stack follows LIFO (Last In First Out) priniciple
* For Insertion and Deletion its complexity is O(1)
* For Accessing and Searching its complexity is O(n)
*/
class Stack {
/**
* initialize stack instances with null
*/
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
/**
* Adding data to Top of the stack
* @param {*} data
* @returns {Stack}
*/
push(data) {
let newNode = new Node(data);
if (!this.first) {
this.first = newNode;
this.last = newNode;
} else {
let temp = this.first;
this.first = newNode;
this.first.next = temp;
}
this.size++;
return this;
}
/**
* Removing data frpm Top of the stack
* @returns {Node.data} The data that is removing from the stack
*/
pop() {
if (!this.first) {
throw Error('UNDERFLOW :::: Stack is empty, there is nothing to remove');
}
let current = this.first;
if (this.first === this.last) {
this.last = null;
}
this.first = current.next;
this.size--;
return current.data;
}
/**
* @returns {Node.data} Top most element of the stack
*/
peek() {
if (!this.first) {
throw Error('Stack is empty');
}
return this.first.data;
}
}
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}