-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsinglyLinkedList.ts
154 lines (141 loc) · 3.26 KB
/
singlyLinkedList.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
148
149
150
151
152
153
154
class LinkedNode<T> {
value: T
next: LinkedNode<T>
constructor(value: T, next: LinkedNode<T>) {
this.value = value
this.next = next
}
}
/**
* SinglyLinkedList
* head / tail
* append
* prepend
* deleteFirst
* deleteLast
* find
* display
* reverse
**/
export class SinglyLinkedList<T> {
head: LinkedNode<T> | null
tail: LinkedNode<T> | null
constructor() {
this.head = null
this.tail = null
}
append(value: T) {
let newNode = new LinkedNode(value, null)
if (!this.head) {
this.head = newNode
this.tail = newNode
return
}
this.tail.next = newNode
this.tail = newNode
return
}
prepend(value: T) {
this.head = new LinkedNode(value, this.head)
}
deleteFirst(): T {
// no node
if (!this.head) {
return
}
// has node
let tmp: T = this.head.value
this.head = this.head.next
if (this.head == null) {
this.tail = null
}
return tmp
}
deleteLast(): T {
// no node
if (!this.head) {
return
}
// one node
if (this.head === this.tail) {
return this.deleteFirst()
}
// multi node
let current = this.head
// find the node before last
while (current.next.next) {
current = current.next
}
let tmp: T = current.next.value
current.next = null
this.tail = current
return tmp
}
find(value: T) {
let curr = this.head
while (curr) {
if (curr.value == value) {
return curr
}
curr = curr.next
}
return null
}
reverse() {
let prev: LinkedNode<T>;
let next: LinkedNode<T>;
let curr: LinkedNode<T> = this.head
while (curr) {
next = curr.next
curr.next = prev
prev = curr
curr = next
}
this.tail = this.head
this.head = prev
}
display() {
let nodes: T[] = []
let curr = this.head
while (curr) {
nodes.push(curr.value)
curr = curr.next
}
console.log(nodes)
}
}
export class SinglyLinkedListForHash<T extends { key: string, value: string }> extends SinglyLinkedList<T> {
constructor() {
super();
}
find(value: { key: string }) {
let curr = this.head
while (curr) {
if (curr.value.key == value.key) {
return curr
}
curr = curr.next
}
return null
}
delete(value: string) {
if (!this.head) {
return
}
if (this.head.value.value === value) {
this.deleteFirst()
return
}
let deleteNode = null
let currentNode = this.head
while (currentNode.next) {
if (currentNode.next.value.value === value) {
deleteNode = currentNode.next
currentNode.next = currentNode.next.next
} else {
currentNode = currentNode.next
}
}
console.log(this)
}
}