Linked List Data Structure | JavaScript – Download



In this video we’re going to learn about linked lists using OOP JavaScript (ES6 Classes). Linked lists are very popular in interview settings and are good to know.

Code:

// 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();
view raw
js_linked_list.js
hosted with ❤ by GitHub

Sponsor: DevMountain Bootcamp
https://goo.gl/6q0dEa

Become a Patron: Show support & get perks!
http://www.patreon.com/traversymedia

Follow Traversy Media:
https://www.facebook.com/traversymedia

https://www.instagram.com/traversymedia

Source

Do you love us?, Please donate to us ,thank you. BTC 38WPVc3xMYmoMp1GcnpDXd1fEzbfgujsCB Etherum 0x6c11844FD079b2490CDd44039e1C2f0940d098dc

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.