Created
August 30, 2015 10:16
-
-
Save niisar/29055ccbe8a401fc6f70 to your computer and use it in GitHub Desktop.
Linked List Class Implementation
This file contains hidden or 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
// Constructor function that sets the values of two properties. | |
function Node(element){ | |
this.element = element; | |
this.next=null; | |
} | |
// Defination for the LList constructor function | |
function LList(){ | |
this.head = new Node("head"); | |
this.find = find; | |
this.insert = insert; | |
this.findPrevious = findPrevious; | |
this.remove = remove; | |
this.display = display; | |
} | |
function find(item){ | |
var currNode = this.head; | |
while(currNode.element != item){ | |
currNode = currNode.next; | |
} | |
return currNode; | |
} | |
function insert(newElement,item){ | |
var newNode = new Node(newElement); | |
var current = this.find(item); | |
newNode.next = current.next; | |
current.next = newNode; | |
} | |
function display(){ | |
var currNode =this.head; | |
while(!(currNode.next == null)){ | |
console.log(currNode.next.element); | |
currNode = currNode.next; | |
} | |
} | |
function findPrevious(item){ | |
var currNode = this.head; | |
while(!(currNode.next == null) && (currNode.next.element != item)){ | |
currNode = currNode.next; | |
} | |
return currNode; | |
} | |
function remove(item){ | |
var prevNode = this.findPrevious(item); | |
if(!(prevNode.next == null)){ | |
prevNode.next = prevNode.next.next; | |
} | |
} | |
// Main Program | |
var cities = new LList(); | |
cities.insert("Conway", "head"); | |
cities.insert("Russellville", "Conway"); | |
cities.insert("Carlisle", "Russellville"); | |
cities.insert("Alma", "Carlisle"); | |
cities.display(); | |
console.log(); | |
cities.remove("Carlisle"); | |
cities.display(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment