Skip to content

Instantly share code, notes, and snippets.

@prashant1k99
Created December 27, 2020 11:02
Show Gist options
  • Save prashant1k99/a9789032eae3dc3f840ef9300d7836a5 to your computer and use it in GitHub Desktop.
Save prashant1k99/a9789032eae3dc3f840ef9300d7836a5 to your computer and use it in GitHub Desktop.
LinkedList Implementation in Js
class Node {
constructor(val) {
this.prev = null
this.val = val
this.next = null
}
}
class LinkedList {
constructor() {
this.clearList()
}
clearList() {
this.head = null
this.size = 0
}
}
LinkedList.prototype.add = function (val) {
let cur
const newNode = new Node(val)
if (this.head === null)
this.head = newNode
else {
cur = this.head
while (cur.next) {
cur = cur.next
}
cur.next = newNode
newNode.prev = cur
}
this.size++
}
LinkedList.prototype.insert = function(val, index) {
if (index < 0 || index > 0 && index > this.size)
return false
else {
const newNode = new Node(val)
if (index == 0) {
newNode.next = this.head
this.head = newNode
} else {
let cur = this.head,
i = 0,
prev
while (i < index) {
i++;
prev = cur,
cur = cur.next
}
newNode.next = cur
newNode.prev = prev
prev.next = newNode
}
this.size++
}
}
LinkedList.prototype.remove = function(index) {
if (index > 0 && index > this.size)
return false
else {
let cur = this.head,
i = 0,
prev = cur
if (index == 0) {
this.head = this.head.next
this.head.prev = null
}
else {
while(i < index) {
i++
prev = cur
cur = cur.next
}
prev.next = cur.next
cur = cur.next
cur.prev = prev
}
this.size--
return this.cur.val
}
}
LinkedList.prototype.removeEl = function (val) {
if (this.size > 0) {
let cur = this.head,
prev = cur
if (cur.val === val) {
cur = cur.next
cur.prev = null
this.size--
return prev.val
} else {
for (let i = 0; i++; i < this.size) {
if (cur.val === val) {
const x = cur.val
prev.next = cur.next
cur = cur.next
cur.prev = prev
return x
} else {
prev = cur
cur = cur.next
i++
}
}
this.size--
return false
}
} else return false
}
LinkedList.prototype.indexOf = function(val) {
if (this.size > 0) {
let cur = this.head,
i = 0
if (cur.val === val) {
return 0
} else {
while(i <= this.size) {
if (cur.val === val) {
return i
} else {
cur = cur.next
i++
}
}
return false
}
} else return false
}
LinkedList.prototype.isEmpty = function() {
return this.size == 0
}
LinkedList.prototype.sizeOfList = function() {
return this.size
}
LinkedList.prototype.printList = function() {
let cur = this.head,
i = 0,
string = ""
for (i; i <= this.size; i++) {
string += " => " + cur.element
cur = cur.next
}
console.log(string)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment