-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinkedlist.js
99 lines (96 loc) · 2.49 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
class LinkedList{
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
// add to the end of the list
append(value){
const newNode = {value: value, next: null};
if(this.tail){
this.tail.next = newNode;
}
this.tail = newNode;
if(!this.head){
this.head = newNode;
}
this.length++;
}
// add to the beginning of the list
prepend(value){
const newNode = {value: value, next: this.head};
this.head = newNode;
if(!this.tail){
this.tail = newNode;
}
this.length++;
}
// insert at a given index
insert(index, value){
if(index >= this.length){
return this.append(value);
}
const newNode = {value: value, next: null};
const leader = this.traverseToIndex(index-1);
const holdingPointer = leader.next;
leader.next = newNode;
newNode.next = holdingPointer;
this.length++;
}
// remove at a given index
remove(index){
if(index >= this.length){
return;
}
const leader = this.traverseToIndex(index-1);
const unwantedNode = leader.next;
leader.next = unwantedNode.next;
this.length--;
}
// traverse to a given index
traverseToIndex(index){
let counter = 0;
let currentNode = this.head;
while(counter !== index){
currentNode = currentNode.next;
counter++;
}
return currentNode;
}
// print the list
printList(){
const array = [];
let currentNode = this.head;
while(currentNode !== null){
array.push(currentNode.value);
currentNode = currentNode.next;
}
return array;
}
// reverse the list
reverse(){
if(!this.head.next){
return this.head;
}
let first = this.head;
this.tail = this.head;
let second = first.next;
while(second){
const temp = second.next;
second.next = first;
first = second;
second = temp;
}
this.head.next = null;
this.head = first;
}
}
const myLinkedList = new LinkedList();
myLinkedList.append(10);
myLinkedList.append(5);
myLinkedList.prepend(1);
myLinkedList.insert(2, 99);
myLinkedList.remove(2);
myLinkedList.reverse();
console.log(myLinkedList.printList());
console.log(myLinkedList);