if(!p){
console.log(new Error('未找到该位置'));
}
}
六、获取结点
------
//获取指定位置结点
LinkList.prototype.getData=function(Pos){
if(!this.head){
console.log(new Error('链表为空'));
return;
}
let i=0;
let p=this.head;
while( i++ < Pos && p){
if(i===Pos){
return p.data;
}
p=p.next;
}
console.log(new Error('未找到该位置'));
}
七、删除结点
------
//按指定位置删除结点
LinkList.prototype.deleteData=function(Pos){
if(!this.head){
console.log(new Error('链表为空'));
return;
}
let p=this.head;
let i=1;
//如果删除的是头结点
if(Pos===1){
p=p.next;
this.head=p;
return;
}
while(p.next){
if(i===Pos-1){
let r=p.next;
p.next=r.next;
return;
}
i++;
p=p.next;
}
console.log(new Error('未找到该位置'));
}
八、清空链表
------
//清空链表
LinkList.prototype.clear=function(){
let q=null;
while(this.head){
q=this.head.next;
this.head=null;
this.head=q;
}
}
### 附:完整源码:
‘use strict’
function LinkList(){
//初始化头结点为null
this.head=null;
//内部类,储存结点数据和next
function Node(data){
this.data=data;
this.next=null;
}
//头插法
LinkList.prototype.insertListByHead=function(data){
const node=new Node(data);
//第一个插入的结点让头结点指向该结点
if(!this.head){
this.head=node;
return;
}
//头插法关键代码
node.next=this.head;
this.head=node;
}
//尾插法
LinkList.prototype.insertListByTail=function(data){
const node=new Node(data);
if(!this.head){
this.head=node;
return;
}
//尾插法关键代码
let p=this.head;
while(p.next){
p=p.next;
}
p.next=node;
}
//指定位置插入
LinkList.prototype.insertListByPos=function(data,Pos){
const node=new Node(data);
//如果插入的位置是第一个,直接调用一次头插法
if (Pos === 1) {
this.insertListByHead(data);
return;
}
//链表为空,直接插入head,忽略Pos
if(!this.head){
this.head=node;
return;
}
let p=this.head;
let i=0; //位置索引
for(;p.next;p=p.next){
i++;
if(i===Pos-1){
node.next=p.next;
p.next=node;
return;
}
}
//当输入的Pos大于链表总长,直接插入到最后
p.next=node;
}
//修改指定位置的值
LinkList.prototype.updateData=function(newData,Pos){
if(!this.head){
console.log(new Error('链表为空,无需更新'));
return false;
}
let i=0;
let p=this.head;
while(p){
if(i===Pos-1){
p.data=newData;
break;
}
i++;
p=p.next;
}
if(!p){
console.log(new Error('未找到该位置'));
}
}
//获取指定位置结点
LinkList.prototype.getData=function(Pos){
if(!this.head){
console.log(new Error('链表为空'));
return;
}
let i=0;
let p=this.head;
while( i++ < Pos && p){
if(i===Pos){
return p.data;
}
p=p.next;
}