-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.ts
More file actions
58 lines (44 loc) · 1.06 KB
/
Stack.ts
File metadata and controls
58 lines (44 loc) · 1.06 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
import { IStack } from "../IStack";
class Node<T> {
private _value: T;
public next: Node<T> | null = null;
public get value(): T {
return this._value;
}
private set value(v: T) {
this._value = v;
}
constructor(value: T) {
this._value = value;
}
}
export class Stack<T> implements IStack<T> {
private top: Node<T> | null = null;
private _lenght: number = 0;
public get lenght(): number {
return this._lenght;
}
private set lenght(v: number) {
this._lenght = v;
}
push(value: T): void {
let item = new Node(value);
if (this.lenght === 0) {
this.top = item;
} else {
item.next = this.top;
this.top = item;
}
this.lenght++;
}
pop(): T {
if (this.lenght === 0) {
throw new Error("No items in the stack");
}
let item = this.top;
this.top = item!.next;
item!.next = null;
this.lenght--;
return item!.value;
}
}