分类分类
更新时间:2026-04-09 16:30:28作者: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;
}
相关
傲视神魔传手游策略游戏13.55 Mv1.0.02026-04-09
下载三国志王道天下策略游戏2.18Gv0.9.8.12026-04-09
下载风云三国手机版策略游戏213.99 M2026-04-09
下载星之海手机版角色扮演2.78Gv1.1.598772026-04-09
下载迪士尼梦幻王国经营养成79.34 Mv11.5.0h2026-04-09
下载TapAim动作射击97.92 Mv2.0.12026-04-09
下载肖邦大冒险九游版策略游戏133.64 Mv1.02026-04-09
下载放松时光与你共享Lo-Fi故事休闲益智951.66 Mv1.4.62026-04-09
下载羽毛球对决体育竞技175.66 Mv4.12026-04-09
下载假面骑士泽兹变身模拟器休闲益智51.91 Mv1.00.302026-04-09
下载餐车厨师烹饪游戏苹果版模拟游戏327.2 Mv8.682026-04-09
下载最终幻想7永恒危机ios版角色游戏1.5Gv3.6.02026-04-09
下载










