-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.ts
144 lines (113 loc) · 2.56 KB
/
index.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
137
138
139
140
141
142
143
144
export interface LinkedListNode<T> {
next?: LinkedListNode<T>;
value: T;
}
export class LinkedListNode<T> implements LinkedListNode<T> {
constructor(value: T, next?: LinkedListNode<T>) {
this.value = value;
this.next = next;
}
}
export interface LinkedList<T> {
head?: LinkedListNode<T>;
length: number;
}
export class LinkedList<T> implements LinkedList<T> {
head?: LinkedListNode<T>;
length = 0;
clear() {
this.head = undefined;
this.length = 0;
}
contains(value: T) {
for (let tmp = this.head; tmp !== undefined; tmp = tmp?.next) {
if (tmp.value === value) {
return true;
}
}
}
find(value: T): LinkedListNode<T> | undefined {
for (let tmp = this.head; tmp !== undefined; tmp = tmp?.next) {
if (tmp.value === value) {
return tmp;
}
}
}
findLast(value: T): LinkedListNode<T> | undefined {
let last;
for (let tmp = this.head; tmp !== undefined; tmp = tmp?.next) {
if (tmp.value === value) {
last = tmp;
}
}
return last;
}
addHead(value: T) {
const node = new LinkedListNode(value, this.head);
this.head = node;
this.length++;
return this.head;
}
addTail(value: T) {
if (!this.head) {
return this.addHead(value);
}
const node = new LinkedListNode(value);
for (let tmp = this.head; tmp !== undefined; tmp = tmp.next) {
if (!tmp.next) {
tmp.next = node;
break;
}
}
this.length++;
return node;
}
remove(value: T) {
for (
let tmp = this.head;
tmp !== undefined && tmp.next?.value === value;
tmp = tmp?.next
) {
if (this.length === 1) {
return this.clear();
}
// Set before to after
tmp.next = tmp.next.next;
}
this.length--;
}
removeHead() {
if (this.length === 1) {
return this.clear();
}
this.head = this.head?.next;
this.length--;
}
removeTail() {
if (this.length === 1) {
return this.clear();
}
let tmp = this.head;
while (tmp?.next?.next) {
tmp = tmp.next;
}
if (tmp) {
tmp.next = undefined;
}
this.length--;
}
}
// const list = new LinkedList<number>();
// console.log(list.addHead(1));
// console.log(list.addHead(2));
// console.log(list.addHead(3));
// console.log(list.addTail(1));
// console.log(list.addTail(2));
// console.log(list.addTail(3));
// list.removeHead();
// list.removeHead();
// list.removeHead();
// list.removeLast();
// list.removeTail();
// list.removeTail();
// console.log(list.find(2));