-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstack.ts
57 lines (45 loc) · 1 KB
/
stack.ts
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
// A simple, immutable stack, imlemented as a linked list.
export abstract class Stack<T> {
abstract peek(): T | undefined;
abstract pop(): Stack<T>;
abstract push(t: T): Stack<T>;
abstract is_empty(): boolean;
}
export function new_stack<T>(): Stack<T> {
return new EmptyStack<T>();
}
class EmptyStack<T> extends Stack<T> {
peek(): T | undefined {
return undefined;
}
pop(): Stack<T> {
return this;
}
push(t: T): Stack<T> {
return new Node(t, this);
}
is_empty(): boolean {
return true;
}
}
class Node<T> extends Stack<T> {
private item: T;
private next: Stack<T>;
constructor(item: T, next: Stack<T>) {
super();
this.item = item;
this.next = next;
}
peek(): T | undefined {
return this.item;
}
pop(): Stack<T> {
return this.next;
}
push(t: T): Stack<T> {
return new Node(t, this);
}
is_empty(): boolean {
return false;
}
}