分类分类
更新时间:2026-11-27 01:27:51作者: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;
}
相关
轻听英语学习办公88.4 MBv2.7.212026-11-26
下载喵喵王国角色扮演1.15Gv00.40.012026-11-26
下载pokecatch游戏休闲益智410Kv1.02026-11-26
下载摇曳露营拼图露营休闲益智82.14 Mv1.7.52026-11-26
下载暗金秘录角色扮演316.84 Mv0.365.02026-11-26
下载AI剪辑图像拍照196.82 MBv21.52026-11-25
下载精灵联萌0.05折版策略游戏13.63 Mv1.0.02026-11-25
下载MilkSU内核管理器实用工具14.29 Mv0.2.62026-11-25
下载百炼仙途角色扮演528.9 Mv10002026-11-25
下载蛊界永生角色扮演407.01 Mv0.4.162026-11-25
下载幻梦无年动作射击276.68 Mv1.1.02026-11-25
下载假人慢打漂泊带土动作射击856.96 Mv0.9.02026-11-25
下载










