-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.js
77 lines (59 loc) · 1.92 KB
/
stack.js
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
function StackLL(){
this.list = new LinkedList();
this.push = function(item) {
// Dodajemo argument sa prednje strane povezane liste
// zato što je ga brže ukloniti iz povezane liste na ovaj način
this.list.addFirst(item);
}
this.pop = function() {
// Provjeravamo da li je povezana lista prazna
if(this.list.count === 0) {
throw new Error("The stack is empty.");
}
// Skladištimo referencu čvora prije brisanja
// da bi smo mogli vratiti njegovu vrijednost
let node = this.list.head;
this.list.removeFirst();
return node.value;
}
this.peek = function() {
if(this.list.count === 0) {
throw new Error("The stack is empty.");
}
// Ovdje samo vraćamo vrijednost bez brisanja
return this.list.head.value;
}
this.count = function() {
return this.list.count;
}
}
function StackArr() {
this.items = [];
this.push = function(item) {
this.items[this.items.length] = item;
}
this.pop = function() {
if(this.items.length === 0) {
throw new Error("The stack is empty");
}
let value = this.items[this.items.length - 1];
if(typeof(value) === "object") {
if(Number.prototype.isPrototypeOf(value) ||
String.prototype.isPrototypeOf(value) ||
Boolean.prototype.isPrototypeOf(value) ||
Symbol.prototype.isPrototypeOf(value)) {
// Deep copy
value = JSON.parse(JSON.stringify(value));
}else{
// Shallow copy
value = Object.assign({}, value);
}
}
delete this.items[this.items.length - 1];
--this.items.length;
return value;
}
this.peek = function() {
return this.items[this.items.length - 1];
}
}