Created
March 2, 2020 15:08
-
-
Save zaingz/ddabed68e4f42df9bfad137bd0d77deb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor (data) { | |
this.data = data | |
this.nextNode = null | |
} | |
} | |
class LinkedList { | |
constructor(){ | |
this.head | |
} | |
isEmpty(){ | |
return !this.head ? true : false | |
} | |
insertAtHead(data){ | |
const node = new Node(data) | |
node.nextNode = this.head | |
this.head = node | |
} | |
insertAtTail(data) { | |
if (this.isEmpty()){ | |
this.insertAtHead(data) | |
}else { | |
const node = new Node(data) | |
let currentNode = this.head | |
while(currentNode.nextNode){ | |
currentNode = currentNode.nextNode | |
} | |
currentNode.nextNode = node | |
} | |
} | |
search(val){ | |
let currentNode = this.head | |
while(currentNode){ | |
if(currentNode.data === val){ | |
console.log('Item found: ', currentNode); | |
return true | |
} | |
currentNode = currentNode.nextNode | |
} | |
console.log('Item not found'); | |
return false | |
} | |
delete(val){ | |
if (this.isEmpty()){ | |
return | |
} | |
if (this.head.data === val){ | |
this.head = this.head.nextNode | |
}else { | |
let currentNode = this.head.nextNode | |
let previousNode = this.head | |
while(currentNode){ | |
if (currentNode.data === val) { | |
previousNode.nextNode = currentNode.nextNode | |
} | |
previousNode = currentNode | |
currentNode = currentNode.nextNode | |
} | |
return | |
} | |
console.log('key not found'); | |
} | |
findMidNode(){ | |
if (this.isEmpty()){ | |
console.log('List is empty') | |
} | |
let slowPointer = this.head | |
let fastPointer = this.head.nextNode | |
while(fastPointer && fastPointer.nextNode){ | |
fastPointer = fastPointer.nextNode.nextNode | |
slowPointer = slowPointer.nextNode | |
} | |
console.log('Middle of list is: ', slowPointer.data); | |
return slowPointer | |
} | |
print(){ | |
if (this.isEmpty()){ | |
console.log('List is empty') | |
} else { | |
let currentNode = this.head | |
const items = [] | |
while(currentNode){ | |
items.push(currentNode.data) | |
currentNode = currentNode.nextNode | |
} | |
console.log(items.join('->')) | |
} | |
} | |
} | |
const list = new LinkedList() | |
list.insertAtHead(50) | |
list.insertAtHead(15) | |
list.insertAtHead(35) | |
list.insertAtTail(5) | |
list.insertAtTail(15) | |
list.insertAtTail(25) | |
list.print() | |
list.findMidNode() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment