Skip to content

Commit

Permalink
add linkedlist
Browse files Browse the repository at this point in the history
  • Loading branch information
pallabez committed Feb 18, 2022
0 parents commit bf1f6b1
Showing 1 changed file with 101 additions and 0 deletions.
101 changes: 101 additions & 0 deletions Linked List/LinkedList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"use strict";

class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}

class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}

add(element) {
var node = new Node(element);

if(this.head == null) {
this.head = node;
this.tail = node;
this.size++;
return;
}

this.tail.next = node;
this.tail = this.tail.next;
this.size++;
}

print() {
var current = this.head;
while(current) {
console.log(current.element);
current = current.next;
}
}

insert(index, element) {
if(index < 0 || index > this.size) {
return console.log('Please enter a valid index');
} else {
var node = new Node(element);
var current;
if(index == 0) {
node.next = this.head;
this.head = node;
if(!this.size) {
this.tail = node;
}
} else {
current = this.head;

while(index - 1) {
current = current.next;
index--;
}

node.next = current.next;
current.next = node;
}

this.size++;
}
}

remove(index) {
if(index == 0) {
this.head = this.head.next;
this.size--;
return;
}

var current = this.head;
while(index - 1) {
if(!current) {
console.log('Index not available')
return;
}
current = current.next;
index--;
}
this.size--;
current.next = current.next.next;
}

sizeOf() {
console.log(this.size);
}
}


var li = new LinkedList();
li.insert(0, 4);
li.add(5);
li.add(6);
li.add(7);
li.remove(2);

li.print();

0 comments on commit bf1f6b1

Please sign in to comment.