-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked_List.js
130 lines (119 loc) · 2.71 KB
/
Linked_List.js
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
// Create the below linked list:
// myLinkedList = {
// head: {
// value: 10
// next: {
// value: 5
// next: {
// value: 16
// next: null
// }
// }
// }
// };
class LinkedList {
constructor(value) {
this.head = {
value: value,
next: null
};
this.tail = this.head;
this.length = 1;
}
printList() {
const array = [];
let currentNode = this.head;
while(currentNode !== null){
array.push(currentNode.value)
currentNode = currentNode.next
}
return array;
}
loop_linked_list(index) {
let search = 0;
let get_node = this.head;
while(get_node != null){
if(search == index){
return get_node;
}
search++;
get_node = get_node.next;
}
}
insert(index, value){
//If the insert value is more than the actual length
if(index > this.length){
return this.append(value)
}
//Get the requsted node that is after the Requested
//Putting this in a Loop because of DRY
let get_node = this.loop_linked_list(index-1);
let node_after = get_node.next
const new_node = {value: value , next: null};
get_node.next = new_node;
new_node.next = node_after;
this.length++;
return this.printList();
}
remove(index){
let get_node = this.loop_linked_list(index);
let get_node_after = this.loop_linked_list(index-1);
get_node_after.next = get_node.next;
this.length--;
}
prepend(value){
if(this.head === undefined){
this.head.value = value;
this.head.next = null;
this.length = 1;
}else{
var new_node = {value: value , next: null};
new_node.next = this.head;
this.head = new_node;
this.length++;
return this;
}
}
append(value) {
if(this.head === undefined){
this.head.value = value;
this.head.next = null;
this.tail = this.head;
this.length = 1;
}else{
var new_node = {value: value ,next: null};
this.tail.next = new_node;
this.tail = new_node;
this.length++;
return this;
}
}
reverse(){
if(this.length === 1){
return this.head;
}
let first = this.head;
this.tail = this.head;
let second = first.next;
while(second != null){
const third = second.next;
second.next = first;
first = second;
second = third;
}
this.head.next = null;
this.head = first;
}
}
let myLinkedList = new LinkedList(10);
myLinkedList.append(5);
myLinkedList.append(16);
myLinkedList.prepend(1);
myLinkedList.insert(2, 99);
myLinkedList.insert(20, 88);
console.log(myLinkedList.length);
myLinkedList.printList();
//myLinkedList.remove(2);
myLinkedList.printList();
myLinkedList.reverse();
myLinkedList.printList();