-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlinkedlistbasedstack.ts
More file actions
49 lines (44 loc) · 1 KB
/
linkedlistbasedstack.ts
File metadata and controls
49 lines (44 loc) · 1 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
import IStack from "./istack";
class ListNode<T> {
constructor(value: T){
this.value = value;
this.prev = null;
this.next = null;
}
public value : T;
public next: ListNode<T>;
public prev: ListNode<T>;
}
class LinkedListBasedStack<T> implements IStack<T> {
private tail : ListNode<T>;
private count: number;
constructor(){
this.tail = null;
this.count = 0;
console.log("creating LinkedListBasedStack")
}
public push(t: T) : void {
if (this.tail === null){
this.tail = new ListNode(t);
} else {
this.tail.next = new ListNode(t);
this.tail.next.prev = this.tail;
this.tail = this.tail.next;
}
this.count++;
}
public pop() : T {
if (this.tail === null){
throw new Error("cannot pop from empty stack!")
} else {
let ret = this.tail.value;
this.tail = this.tail.prev;
this.count--;
return ret;
}
}
public size() : number {
return this.count;
}
}
export default LinkedListBasedStack