-
Notifications
You must be signed in to change notification settings - Fork 5
/
linked-list.ts
147 lines (112 loc) · 2.66 KB
/
linked-list.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
145
146
147
class Node<T> {
public value: T;
public next: Node<T>;
constructor(value: T) {
this.value = value;
}
}
export class LinkedList<T> {
private tail: Node<T>;
private head: Node<T>;
private _length: number;
constructor() {
this.tail = this.head = null;
this._length = 0;
}
// O(1)
public push(value: T): number {
const node = new Node(value);
if (this._length === 0) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
return ++this._length;
}
// O(n)
public pop(): T {
let value;
if (this._length === 1) {
value = this.head.value;
this.tail = this.head = null;
this._length--;
} else if (this._length > 1) {
value = this.tail.value;
const penultimate = this.getNode(this._length - 2);
penultimate.next = null;
this.tail = penultimate;
this._length--;
}
return value;
}
// O(n)
public get(index: number): T {
const node = this.getNode(index);
if (node) {
return node.value;
}
}
// O(n)
public insert(index: number, value: T): number {
let newNode = new Node(value);
if (index === 0) {
if (this._length > 1) {
newNode.next = this.head;
this.head = newNode;
this._length++;
} else {
this.tail = this.head = newNode;
this._length = 1;
}
} else if (index > 0 && index < this._length) {
const previous = this.getNode(index - 1);
[newNode.next, previous.next] = [previous.next, newNode];
if (index === this._length - 1) {
this.tail = newNode.next;
}
this._length++;
}
return this._length;
}
// O(n)
public delete(index: number): T {
let deleted: Node<T>;
if (index === 0) {
deleted = this.head;
if (this._length > 1) {
this.head = this.head.next;
this._length--;
} else {
this.tail = this.head = null;
this._length = 0;
}
} else if (index > 0 && index < this._length) {
const previous = this.getNode(index - 1);
deleted = previous.next;
if (index === this._length - 1) {
previous.next = null;
this.tail = previous;
} else {
previous.next = previous.next.next;
}
this._length--;
}
return deleted ? deleted.value : void 0;
}
// O(1)
public get length(): number {
return this._length;
}
// O(n)
private getNode(index: number): Node<T> {
if (this._length > 0 && index < this._length) {
let count = index;
let node = this.head;
while(count--) {
node = node.next;
}
return node;
}
}
}