使用JavaScript实现链表的插入、删除、求长度等方法。
"use strict"
//结点类
var Node = function(){
this.data = null;
this.next = null;
}
//链表类
var LinkList = function(){
var first = new Node();
//计算链表长度
var length = function(){
let p = first.next;
let count = 0;
while(p!=null){
p=p.next;
count++;
}
return count;
}
//在从左到右第i个结点后插入结点,0表示在头插入
var insert = function(node,index){
if(arguments.length===1){
this.push(node);
return;
}
let newNode = new Node();
newNode.data = node;
let p = first;
for(let i=0;i<index;i++){
if(p.next!=null){
p = p.next;
}else{
newNode.next = p.next;
p.next = newNode;
return;
}
}
newNode.next = p.next;
p.next = newNode;
return;
}
//尾插法插入结点
var push = function(node){
let newNode = new Node();
newNode.data = node;
let p = first;
while(p.next!=null){
p = p.next;
}
p.next = newNode;
}
//删除尾结点
var pop = function(){
let p = first,preNode=null;
while(p.next!=null){
preNode = p;
p = p.next;
}
preNode.next = null;
return p.data;
}
//头插法插入结点
var unshift = function(node){
let newNode = new Node();
newNode.data = node;
newNode.next = first.next;
first.next = newNode;
}
//删除头结点
var shift = function(node){
let p = first.next;
first.next = p.next;
return p.data;
}
//从头数删除索引为i的结点,0表示删除第一个结点
var remove = function(index){
if(typeof index!=="number"){
throw Error("the argument of remove must be a number!");
return;
}
if(index < 0){
throw Error("the input can't be negative number!");
return;
}
let p = first,preNode = null;
for(let i=0;i<=index;i++){
if(p.next!==null){
preNode = p;
p = p.next;
}else{
throw Error("the input is bigger than the length of list!");
return;
}
}
preNode.next = p.next;
return p.data;
}
//获取链表数组
var getList = function(){
let arr = [];
let p = first;
let count = 0;
while(p.next!=null){
p = p.next;
//console.log(p);
arr[count++] = p.data;
if(count>100){
alert("死循环了");
break;
}
}
return arr;
}
return {
length:length,
insert:insert,
push:push,
unshift:unshift,
shift:shift,
pop:pop,
remove:remove,
getList:getList
}
}
var list = new LinkList();
list.push(0);
list.push("id");
list.push(2);
list.unshift(-1);
list.insert(-2,0);
console.log(list.getList());
console.log("pop:",list.pop());
console.log("shift:",list.shift());
console.log("remove:",list.remove(0));
console.log("lenght:",list.length());
console.log(list.getList());