Skip to content

Instantly share code, notes, and snippets.

@gohilumesh
Created July 10, 2018 05:43
Show Gist options
  • Save gohilumesh/7bf294ec6e75301bdda666961949460c to your computer and use it in GitHub Desktop.
Save gohilumesh/7bf294ec6e75301bdda666961949460c to your computer and use it in GitHub Desktop.
class Node{
constructor(data) {
this.data = data;
this.next = null;
}
}
class LL {
constructor() {
this.head = null;
}
insert(data) {
if (!data) {
return null;
}
let node = new Node(data);
let current = this.head;
if (current === null) {
this.head = node;
} else {
while(current.next) {
current = current.next;
}
current.next = node;
}
}
remove(data) {
if (this.head && this.head.data === data) {
this.head = this.head.next;
} else {
let current = this.head;
let prev = null;
while(current) {
if (current.data === data) {
prev.next = current.next;
break;
}
prev = current;
current = current.next;
}
}
}
find(data) {
let current = this.head;
while(current) {
if (current.data === data) {
return current;
}
current = current.next;
}
return null;
}
print() {
let current = this.head;
while(current) {
console.log(current.data);
current = current.next;
}
}
reverse() {
let current = this.head;
let prev = null;
let next = null;
while(current) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
this.head = prev;
}
nToLast(k) {
let current = this.head;
for (let i=0; i < k-1; i++) {
current = current.next;
}
let p1 = this.head;
while(current.next) {
p1 = p1.next;
current = current.next;
}
return p1;
}
hasLoop() {
let p1 = this.head;
let p2 = this.head;
while(p2 && p2.next && p2.next.next) {
p1 = p1.next;
p2 = p2.next.next;
if (p1 === p2) {
return true;
}
}
return false;
}
}
let myList = new LL();
myList.insert('a');
myList.insert('b');
myList.insert('c');
myList.insert('d');
myList.insert('e');
myList.insert('f');
myList.remove('b');
console.log(myList.find('e')); // e --> f
console.log(JSON.stringify(myList)); // a --> c --> d --> e --> f --> null
myList.reverse(); // reverse the list f --> e --> d --> c --> a --> null
console.log(JSON.stringify(myList));
console.log(myList.nToLast(2)); // c --> a -- > next
console.log(myList.hasLoop()); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment