-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.ts
136 lines (124 loc) · 3.54 KB
/
LinkedList.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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//---------------------------------- Linked List ------------------------------
class Node<T> {
_val:T | null;
_next:Node<T> | null;
constructor(val:T|null=null, next:Node<T>|null=null) {
this._val = val;
this._next = next;
}
hasVal(val:T):boolean {
return this._val === val;
}
}
interface ILinkedListIterator<T> {
hasNext():boolean,
next():void,
getValue():T|null,
setToHead():void
}
export class LinkedList<T> {
_head:Node<T> | null;
private _length:number = 0;
constructor() {
this._head = null;
}
push(val:T|null):void {
if (val!= null) {
this._head = new Node<T>(val, !this._head ? null : this._head);
this._length++;
}
}
pop():T|null {
if (this._head) {
var n = this._head;
if (this._head._next) {
this._head = this._head._next;
} else {
this._head = null;
}
this._length--;
return n._val;
}
this._length = 0;
return null;
}
remove(val:T):T|null {
if (val != null) {
var n = this._head;
var m = n;
if (n) {
while (n._next) {
if (n.hasVal(val) && m) {
m._next = n._next
this._length--;
return n._val;
}
m = n;
n = n._next;
}
}
}
return null;
}
insertBefore(val:T|null, before:T|null):void {
if (val != null && before != null) {
if (!this._head || this._head.hasVal(before)) {
this._head = new Node<T>(val);
}
var n:Node<T> = this._head;
var m:Node<T> = n;
while (n._next) {
if (n.hasVal(before)) {
m._next = new Node<T>(val, n);
this._length++;
break;
}
m = n;
n = n._next;
}
}
}
insertAfter(val:T|null, after:T|null):void {
if (val != null && after != null) {
var n = this.find(after);
if (n) {
n._next = new Node<T>(val, n._next);
}
}
}
findValByObjectKey<U extends keyof T>(key:U, value:any):T|null {
if (key != null && this._head) {
var n:Node<T> = this._head;
while (n._next) {
if (n._val !== null && n._val[key] === value) {
return n._val;
}
n = n._next;
}
}
return null;
}
find(val:T|null):Node<T>|null {
if (val != null && this._head) {
var n:Node<T> = this._head;
while (n._next) {
if (n.hasVal(val)) {return n;}
n = n._next;
}
}
return null;
}
getIterator():ILinkedListIterator<T> {
let n:Node<T>|null = this._head;
return {
hasNext:():boolean => {return n !== null},
next:():void => {
if (n) {
n = n._next;
}
},
getValue:():T|null => { if (n) return n._val; else return null; },
setToHead:():void => {n = this._head;}
}
}
}