-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedlist.js
138 lines (112 loc) · 2.9 KB
/
linkedlist.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
131
132
133
134
135
136
137
138
class linkedlist {
constructor(value){
this.head = {
value: value,
next: null
}
this.tail = this.head;
this.length = 1;
}
append(value){
const newNode = {
value:value,
next: null
}
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value){
const newNode = {
value: value,
next: null
};
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
printList(){
let currentNode = this.head;
const array = [];
while(currentNode !== null){
array.push(currentNode.value);
currentNode = currentNode.next;
}
return array;
}
traverseIndex(index){
let counter = 0;
let currentNode = this.head;
while(counter !== index){
currentNode = currentNode.next;
counter++;
}
return currentNode;
}
insert(index, value){
// if index is greater than the length
if(index >= this.length){
this.append(value);
}
//if index is equal to zero
if(index == 0){
this.prepend(value);
}
const newNode = {
value:value,
next: null
};
let leaderNode = this.traverseIndex(index-1);
const leaderNodeNext = leaderNode.next;
leaderNode.next = newNode;
newNode.next = leaderNodeNext;
this.length++;
return this.printList();
}
remove(index){
if(index >= this.length || index < 0){
return "enter correct index";
}
if(index == 0){
this.head = this.head.next;
return;
}
10 - 1- 5 - 16
let leaderNode = this.traverseIndex(index -1);
const unwantedNode = leaderNode.next;
leaderNode.next = unwantedNode.next;
this.length--;
return this.printList();
}
reverse(){
//if size of list is equal to 1
if(!this.head.next){
return this;
}
this.tail = this.head;
let first = this.head;
let second = first.next;
while(second){
let temp = second.next;
second.next = first;
first = second;
second = temp;
}
this.head.next = null;
this.head = first;
return this;
}
}
const myLinkedList = new linkedlist(10);
myLinkedList.append(5);
myLinkedList.append(16);
myLinkedList.insert(1,99);
// console.log(myLinkedList.printList());
// myLinkedList.remove(2);
// console.log(myLinkedList.printList());
// myLinkedList.remove(0);
//console.log(myLinkedList.printList());
myLinkedList.reverse();
console.log(myLinkedList.printList());