A5下载文章资讯

分类分类

JavaScript 单链表操作

2015-09-23 17:06作者:yezheng

本文小编将为大家介绍使用JavaScript实现单链表操作,朋友们可以看来一下,有问题请跟我分享,谢谢!

1. [JavaScript]代码如下:

//链表节点类

var Node = function(v){

this.data =v;

this.next = null;

}

//单链表

var SingleLink = function(v){

this.head = new Node(null);//作为头结点,数据域不保存值

this.insertHead = function(v){//头插法

var q = new Node(v);

q.next = this.head.next;

this.head.next=q;

}

this.insertTail = function(v){//尾插法

var p = this.head;

var q = new Node(v);

while(p.next!=null){

p = p.next;

}

p.next = q;

}

//获取第n个节点,头结点为第0个节点

this.getNodeByIndex = function(n){

var p = this.head;

var i = 0;

while(p.next!=null&& i<n){

p = p.next;

i++;

}

return p;

}

//计算链表的长度,不包括头结点

this.getLength = function(){

var p =this.head;

var len = 0;

while(p.next!=null){

p=p.next;

len++;

}

return len;

}

//删除指定位置的节点

this.removeAt = function(num){//传入1表示删除第一个带数据的节点

if(num<0){

return false;

}

var preNode = getNodeByIndex(num-1);

var q = preNode.next;

preNode.next = preNode.next.next;

q.next = null;

}

//查找指定值节点

this.getNodeByValue = function(v){

var p = this.head;

while(p.next!=null){

p = p.next;

if(p.data ===v){

return p;

}

}

return null;

}

/**

* 返回链表数据组成的字符串

* @return {[type]} [description]

*/

this.printLink = function(){

var p =this.head;

var arr =[];

while(p.next!=null){

p = p.next;

arr.push(p.data);

}

return arr.join(' ');

}

//是否包含某个值

/**

* 是否包含某值,返回布尔值

* @param {[type]} v [description]

* @return {Boolean} [description]

*/

this.isContainValue = function(v){

var p = this.head;

while(p.next!=null){

p = p.next;

if(p.data ===v){

return true;

}

}

return false;

}

/**

* 返回数组,包含的重复值

* @return {[type]} [description]

*/

this.containRepeat = function(){

var p =this.head;

var arr = [],obj={};

while(p.next != null){

p = p.next;

var q = p;

while(q.next != null){

q=q.next;

if(p.data === q.data &&obj[q.data] ==undefined){

obj[p.data] = 1;

arr.push(p.data);

}

}

}

return arr;

}

}

/**

* 反转链表,返回一个新的链表

* @param {[type]} singleLink [description]

* @return {[type]} [description]

*/

function reverseSingleLink (singleLink){

var p =singleLink.head;

var arr = [];

while(p.next!=null){

p = p.next;

arr.push(p.data);

}

singleLink.next = null;

var newLink = new SingleLink();

for(var i = arr.length-1;i>=0;i--){

newLink.insertTail(arr[i]);

}

return newLink;

}

展开全部

相关

说两句网友评论
    我要跟贴
    取消