JavaScript数据结构单链表的封装
function LiskedList(){
function Nodes(data){
this.data = data;
this.next = null;
}
this.header = null;
this.length = 0;
LiskedList.prototype.append = function(data) {
var newNode = new Nodes(data);
if(this.length == 0){
this.header = newNode
}else{
var currentNode = this.header
while(currentNode.next){
currentNode = currentNode.next
}
currentNode.next = newNode
}
this.length +=1
}
LiskedList.prototype.insert = function(position,data) {
if(position<0 || position>this.length) return false
var newNode = new Nodes(data)
if(this.length = 0){
newNode.next = this.header
this.header = newNode
}else{
var prevNode = null
var index = 0
var currentNode = this.header
while (index++<position) {
prevNode =currentNode
currentNode = currentNode.next
}
newNode.next = currentNode
prevNode.next = newNode
}
this.length +=1
return true
}
LiskedList.prototype.get = function(position){
if(position<0 || position>=this.length){
}
index = 0;
currentNode = this.header
while(index++ < position){
currentNode = currentNode.next
}
return currentNode.data
}
LiskedList.prototype.indexOf = function (element) {
index = 0
currentNode = this.header
while (index < this.length){
if (currentNode.data == element) {
return index
}else{
currentNode = currentNode.next
index++
}
}
return -1
}
LiskedList.prototype.update = function(position,data){
if(position<0||position>=this.length){
return false
}
index =0
currentNode = this.header
while(index<position){
currentNode = currentNode.next
index++;
}
currentNode.data = data
return true
}
LiskedList.prototype.removeAt = function(position){
if(position<0 || position>= this.length){
return false
}
if (position==0) {
this.header = this.header.next
}else{
index = 0
prevNode = null;
currentNode = this.header
while(index++<position){
prevNode = currentNode
currentNode = currentNode.next
}
prevNode.next = currentNode.next
}
this.length-=1
return true
}
LiskedList.prototype.remove = function(data){
index = 0
prevNode = null
currentNode = this.header
while (index <this.length){
if(currentNode.data == data){
if(index == 0){
this.header = currentNode.next
return true
}else{
prevNode.next = currentNode.next
return true
}
}else{
prevNode = currentNode
currentNode= currentNode.next
}
}
return false
}
LiskedList.prototype.isEmpty = function(){
return this.length == 0
}
LiskedList.prototype.size = function(){
return this.length
}
LiskedList.prototype.toString = function(){
var currentNode = this.header
var listString = ''
while (currentNode){
listString += currentNode.data+" "
currentNode = currentNode.next
}
return listString
}
}
var list = new LiskedList()
list.append('l')
list.append('i')
list.append('s')
list.append('t')
list.update(2,'ss')
list.remove('l')
console.log(list.toString());