-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList.ts
66 lines (52 loc) · 1.13 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
class LinkedListNode {
data = null
nextNode: LinkedListNode = null
constructor(data: any) {
this.data = data
}
}
class LinkedList {
head: LinkedListNode = null
isEmpty() {
return this.head === null
}
size() {
let current = this.head
let count = 0
while (!!current) {
count += 1
current = current.nextNode
}
return count
}
add(data: any) {
const newNode = new LinkedListNode(data)
newNode.nextNode = this.head
this.head = newNode
}
search(key: any) {
let current = this.head
while (!!current) {
if (current.data === key) return current
else current = current.nextNode
}
return null
}
insert(data: any, index: number) {
if (index === 0) this.add(data)
if (index > 0) {
const newNode = new LinkedListNode(data)
let position = index
let current = this.head
while (position > 1) {
current = newNode.nextNode
position -= 1
}
let previous = current
let next = current.nextNode
previous = current
newNode.nextNode = next
}
}
}
type LinkedNode = LinkedListNode