class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
class linkedList {
constructor(head = null) {
this.head = head;
this.size = 0;
}
insertAtFirst(data) {
this.head = new Node(data, this.head);
this.size++;
}
insertAtLast(data) {
if (this.head === null) {
this.head = new Node(data);
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = new Node(data);
}
this.size++;
}
insertAtIndex(data, index) {
if (index > 0 && index > this.size) {
return;
}
if (index === 0) {
insertAtFirst(data);
return;
}
const node = new Node(data);
let count = 0;
let previous, next;
let current = this.head;
while (count < index) {
count++;
previous = current;
current = current.next;
}
node.next = current;
previous.next = node;
this.size++;
}
getAt(index) {
let current = this.head;
let count = 0;
while (current) {
if (count == index) {
console.log(current.data);
}
count++;
current = current.next;
}
return null;
}
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--;
}
clearList() {
this.head = null;
this.size = 0;
}
print() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
}
let ll = new linkedList();
ll.insertAtFirst(100);
ll.insertAtFirst(200);
ll.insertAtFirst(300);
ll.insertAtLast(400);
ll.insertAtIndex(500, 3);
ll.getAt(3);
ll.removeAt(1);
ll.print();
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (1)
Hey ๐๐ผ
This looks like a good post here. Can you share this in full on DEV?
DEV generally asks that folks share their posts in full if possible, and there is tooling provided to make it so that it's relatively easy to repost from outside blogs.
Hope you'll consider sharing the full post going forward.
Also don't hesitate to put colors on your
codeblock
like this example for have to have a better understanding of your code ๐