Skip to content

Instantly share code, notes, and snippets.

@rshivkumar95
Last active July 21, 2019 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rshivkumar95/a965473b0fb2400c5ee8feaa4c78649f to your computer and use it in GitHub Desktop.
Save rshivkumar95/a965473b0fb2400c5ee8feaa4c78649f to your computer and use it in GitHub Desktop.
Linked List Implementation
// LINKEDLIST NODE
class Node {
constructor(data){
this.data = data;
this.next = null;
}
}
// LINKEDLIST IMPLEMENTATION
class LinkedList {
constructor(){
this.head = null;
this.size = 0;
}
add(data) {
let node = new Node(data);
if(this.head === null) {
this.head = node;
}
else {
let curr = this.head;
while(curr.next != null) {
curr = curr.next;
}
curr.next = node;
}
this.size++;
}
//
insertAt(data, location) {
if(location > 0 && location > this.size) {
return false;
}
else {
let curr, prev;
let node = new Node(data);
if(location === 0) {
node.next = this.head;
this.head = node;
}
else {
curr = this.head;
let i = 0;
while(i < location){
i++;
prev = curr;
curr = curr.next;
}
prev.next = node;
node.next = curr;
}
}
this.size++;
}
removeFrom(location) {
if(location > 0 && location > this.size) {
return false;
}
else {
let curr = this.head, prev;
if(location === 0) {
this.head = curr.next;
}
else {
curr = this.head;
let i = 0;
while(i < location){
i++;
prev = curr;
curr = curr.next;
}
prev.next = curr.next;
}
this.size--;
return curr.data;
}
}
removeElement(data) {
let curr = this.head,
prev = null;
while(curr !== null) {
if(curr.data === data) {
if(prev === null) {
this.head = curr.next;
}
else {
prev.next = curr.next;
}
this.size--;
return curr.data;
}
prev = curr;
curr = curr.next;
}
return -1;
}
printList() {
var curr = this.head;
while(curr !== null) {
console.log(curr.data);
curr = curr.next;
}
}
getSize() {
return this.size;
}
isEmpty() {
return this.size === 0;
}
}
// LINKEDLIST USAGE
let llist = new LinkedList();
console.log('is Empty :: ' + llist.isEmpty());
console.log('Size :: '+ llist.getSize());
llist.add(1);
llist.add(3);
llist.add(4);
llist.add(5);
llist.add(6);
llist.insertAt(2, 1);
console.log('removed :: ' + llist.removeFrom(5));
console.log('removed :: ' + llist.removeElement(1));
console.log('is Empty :: ' + llist.isEmpty());
console.log('Size ::' + llist.getSize());
llist.printList();
"is Empty :: true"
"Size :: 0"
"removed :: 6"
"removed :: 1"
"is Empty :: false"
"Size ::4"
2
3
4
5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment