分类分类
更新时间:2026-08-08 18:02:04作者: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;
}
相关
星球小队策略游戏316.49 MBv1.15.366.638912026-08-08
下载超市大亨3D经营养成253.14 MBv10.252026-08-08
下载绝世武林角色扮演453.09 MBv1.8.14162026-08-08
下载Crush Crush手机版经营养成124.86 Mv0.4482026-08-08
下载消消大亨经营养成13.56 Mv1.0.02026-08-08
下载endacopia手机版冒险游戏1.43Gv1.0.02026-08-08
下载最强帮主角色扮演143.91 Mv9991.12026-08-08
下载战西游手游折扣版策略游戏13.77 Mv1.02026-08-08
下载富豪物语创业时代官方版经营养成215.01 Mv3.0.12026-08-08
下载咒术回战爱憎乱斗手游动作射击291.7 Mv1.0.02026-08-08
下载三国吧兄弟折扣版策略游戏380.04 Mv1.0.02026-08-08
下载代号97动作射击277.47 Mv1.0.72026-08-08
下载










