-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.ts
131 lines (110 loc) · 3.37 KB
/
test.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
class LinkedList {
private head: LinkedListItem;
constructor(item: LinkedListItem) {
this.head = item;
}
// Adds the element at the end of the linked list
append(val) {
let currentItem: LinkedListItem = this.head;
let newItem = new LinkedListItem(val);
if (!currentItem) {
this.head = newItem;
} else {
while (true) {
if (currentItem.next) {
currentItem = currentItem.next;
} else {
currentItem.next = newItem;
break;
}
}
}
}
// Add the element at the beginning of the linked list
prepend(val) {
let newItem = new LinkedListItem(val);
let oldHead = this.head;
this.head = newItem;
newItem.next = oldHead;
}
// Adds the element at a specific position inside the linked list
insert(val, previousItem: LinkedListItem) {
let newItem: LinkedListItem = new LinkedListItem(val);
let currentItem: LinkedListItem = this.head;
if (!currentItem) {
this.head = newItem;
} else {
while (true) {
if (currentItem === previousItem) {
let tempNextItem = previousItem.next;
currentItem.next = newItem;
newItem.next = tempNextItem;
break;
} else {
currentItem = currentItem.next;
}
}
}
}
delete(val) {
var currentItem = this.head;
if (!currentItem) {
return;
}
if (currentItem.value === val) {
this.head = currentItem.next;
} else {
var previous = null;
while (true) {
if (currentItem.value === val) {
if (currentItem.next) { // special case for last element
previous.next = currentItem.next;
} else {
previous.next = null;
}
currentItem = null; // avoid memory leaks
break;
} else {
previous = currentItem;
currentItem = currentItem.next;
}
}
}
}
showInArray() {
let arr = [];
let currentItem = this.head;
while (true) {
arr.push(currentItem.value);
if (currentItem.next) {
currentItem = currentItem.next;
} else {
break;
}
}
return arr;
}
}
class LinkedListItem {
value: any;
next: LinkedListItem;
constructor(val) {
this.value = val;
this.next = null;
}
}
let head = new LinkedListItem(4);
let linkedList = new LinkedList(head);
linkedList.append(10);
linkedList.append(2);
linkedList.append(20);
linkedList.append(5);
console.log(linkedList.showInArray()); // Should log 4, 10, 2, 20, 5
linkedList.prepend(1);
linkedList.prepend(100);
console.log(linkedList.showInArray()); // Should log 100, 1, 4, 10, 2, 20, 5
linkedList.delete(1);
linkedList.delete(10);
console.log(linkedList.showInArray()); // Should log 100, 4, 2, 20, 5
linkedList.insert(200, head);
console.log(linkedList.showInArray()); // Should log 100, 200, 4, 2, 20, 5