分类分类
更新时间:2026-02-18 20:43:59作者: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;
}
相关
归墟战纪策略游戏262.92 MBv3.95802026-02-14
下载爆裂老奶策略游戏209.43 MBv1.0.112026-02-14
下载超能下蛋鸭策略游戏395.4 MBv1.2.82026-02-14
下载你好盒子实用工具12.1 MBv2.2.852026-02-14
下载我在峡谷当牛马休闲益智87.95 MBv0.7.12026-02-14
下载抽卡监狱2策略游戏190.75 MBv1.4.92026-02-14
下载Campus社交通讯94.36 MBv1.19.02026-02-14
下载冒险传奇角色扮演141.73 Mv9991.12026-02-14
下载心动次元app社交通讯43.96 Mv1.0.1.32026-02-14
下载致亲爱的我角色扮演1.63Gv1.02026-02-14
下载狼伴侣游戏手机版冒险游戏155.6 Mv1.02026-02-14
下载Loclike社交通讯169.08 Mv2.2.112026-02-14
下载










