This repository was archived by the owner on Sep 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathstack.js
More file actions
113 lines (103 loc) · 2.01 KB
/
stack.js
File metadata and controls
113 lines (103 loc) · 2.01 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* @author Rashik Ansar and Luiz Guerra
*
* 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)
*
* @author Jan Tabacki
* Fix in toString method, display all elements and get data property instead of element
* which does no exist.
*/
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;
}
/**
* @returns size of the Stack
*/
size() {
return this.size;
}
/**
* @returns if Stack is empty
*/
isEmpty() {
return this.size == 0;
}
/**
* clears the Stack
*/
clear() {
this.first = null;
this.last = null;
this.size = 0;
}
/**
* @returns the Stack
*/
toString() {
let str = "";
let aux = this.first;
while (aux) {
str += aux.data + " ";
aux = aux.next;
}
return str;
}
}
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}