-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList.js
145 lines (116 loc) · 2.64 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
139
140
141
142
143
144
145
// Construct Single Node
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
// Create/Get/Remove Nodes From Linked List
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// Insert first node
insertFirst(data) {
this.head = new Node(data, this.head);
this.size++;
}
// Insert last node
insertLast(data) {
let node = new Node(data);
let current;
// If empty, make head
if (!this.head) {
this.head = node;
} else {
current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
this.size++;
}
// Insert at index
insertAt(data, index) {
// If index is out of range
if (index > 0 && index > this.size) {
return;
}
// If first index
if (index === 0) {
this.insertFirst(data);
return;
}
const node = new Node(data);
let current, previous;
// Set current to first
current = this.head;
let count = 0;
while (count < index) {
previous = current; // Node before index
count++;
current = current.next; // Node after index
}
node.next = current;
previous.next = node;
this.size++;
}
// Get at index
getAt(index) {
let current = this.head;
let count = 0;
while (current) {
if (count == index) {
console.log(current.data);
}
count++;
current = current.next;
}
return null;
}
// Remove at index
removeAt(index) {
if (index > 0 && index > this.size) {
return;
}
let current = this.head;
let previous;
let count = 0;
// Remove first
if (index === 0) {
this.head = current.next;
} else {
while (count < index) {
count++;
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.size--;
}
// Clear list
clearList() {
this.head = null;
this.size = 0;
}
// Print list data
printListData() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
}
const ll = new LinkedList();
ll.insertFirst(100);
ll.insertFirst(200);
ll.insertFirst(300);
ll.insertLast(400);
ll.insertAt(500, 3);
// ll.clearList();
// ll.getAt(2);
ll.printListData();