Created
May 1, 2018 14:48
-
-
Save hillal20/aa6b2d1a381635fda73cffb62a4d5669 to your computer and use it in GitHub Desktop.
linked list
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
function Linkedlist(){ | |
this.head = null; | |
} | |
Linkedlist.prototype.isEmpty = function(){ | |
return this.head === null; | |
}; | |
////////////////////////////////////// | |
Linkedlist.prototype.size = function(){ | |
let current = this.head; | |
let count = 0; | |
while(current !== 0){ | |
count ++; | |
current = current.next; | |
} | |
return current; | |
}; | |
////////////////////////////////////////// | |
Linkedlist.prototype.prepend = function(x){ | |
let newNode = { | |
data: x , | |
next: this.head | |
} | |
this.head = newNode // to be the first one in the list | |
} | |
////////////////////////////////////////////// | |
Linkedlist.prototype.append = function(x){ | |
let newNode = { | |
data:x, | |
next: null // the last one in the list | |
} | |
if (this.isEmpty()){ | |
this.head = newNode; | |
return; | |
} | |
let current = this.head | |
while (current.next !== null) { | |
// stop at the the one before the last , becuase the last is null which is the newNode | |
current = current.next; | |
} | |
current.next = newNode; | |
} | |
/////////////////////////// | |
Linkedlist.prototype.contains =function(x){ | |
let current= this.head; | |
while(current !== null){ | |
if ( current.data === x){ | |
return true; | |
} | |
else{ | |
current= current.next; | |
} | |
} | |
return false; | |
} | |
////////////////////////////// | |
Linkedlist.prototype.remove = function(x){ | |
if (!this.contains(x)){ | |
return; /// there is no x inside | |
} | |
if ( this.head.data === x){ | |
this.head = this.head.next | |
return ; | |
} | |
let previous = null; | |
let current = this.head; | |
while(current.data !== x){ | |
previous = current; | |
current = current.next | |
} | |
prevois.next = current.next | |
}; | |
////////////////////// | |
Linkedlist.prototype.print = function(){ | |
let output = "["; | |
current= this.head; | |
while(current !== null){ | |
output += current.data; | |
if(current.next !== null ){ | |
output += ","; | |
} | |
current= current.next | |
} | |
output += "]"; | |
console.log(output) | |
} | |
let list = new Linkedlist(); | |
list.prepend(10); | |
list.append(30); | |
list.append(24); | |
list.append(67); | |
list.append(77); | |
list.print(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment