class Node{
constructor(value){
this.value = value;
this.next = null;
}
}
class LinkedList{
head = null;
length = 0;
isEmpty(){
if(this.length === 0 || this.head === null){
return true;
}
return false;
}
push(value){
let node = new Node(value);
if(this.head === null){
this.head = node;
}else{
let tempNode = this.head;
while(tempNode.next !== null){
tempNode = tempNode.next;
}
tempNode.next = node;
}
this.length++;
}
find(value){
if(this.isEmpty()){
console.log('这是一个空链表!');
return null;
}
let tempNode = this.head;
if(tempNode.value === value){
return tempNode;
}
while(tempNode.next !== null){
tempNode = tempNode.next
if(tempNode.value === value){
return tempNode;
}
}
console.log('当前链表没有找到值为'+value+'的节点!');
return null;
}
insertAfer(value, preValue){
const preNode = this.find(preValue);
const node = new Node(value);
if(preNode === null){
console.log('没有找到值为'+preValue+'的节点,插入失败!');
return;
}
node.next = preNode.next;
preNode.next = node;
this.length++;
console.log('插入成功!');
}
findPrevious(value){
if(this.isEmpty()){
console.log('这是一个空链表!');
return null;
}
const tempNode = this.head;
if(tempNode.value === value){
console.log('值'+value+'是第一个节点,没有前节点!');
return;
}
while(tempNode.next !== null){
if(tempNode.next.value === value){
return tempNode;
}
tempNode = tempNode.next;
}
console.log('没有找到值为'+value+'的前置节点!');
return null;
}
remove(value){
if(this.isEmpty()){
console.log('这是一个空链表!');
return null;
}
const head = this.head;
const node = this.find(value);
if(!node){
console.log(`没有找到值为${value}的节点`);
return;
}
const preNode = this.findPrevious(value);
if(!preNode){
this.head = node.next;
}
preNode.next = node.next;
this.length--;
}
size(){
return this.length;
}
indexof(value){
if(this.isEmpty()){
console.log('这是一个空链表!');
return null;
}
const tempNode = this.head;
let index = 0;
if(tempNode.value === value){
return index
}
while(tempNode.next !== null){
tempNode = tempNode.next;
index++;
if(tempNode.value === value){
return index;
}
}
console.log(`没有找到值为${value}的节点!`);
return -1;
}
removeAt(index){
if(this.isEmpty()){
console.log('这是一个空链表!');
return null;
}
if(index < 0){
console.log('非法参数!');
return;
}
if(index >= this.length){
console.log('删除的位置超过了当前链表长度!');
return;
}
if(index === 0){
this.head = this.head.next;
console.log('删除成功!');
return;
}
let current = this.head;
let curIndex = 0;
let preNode;
while(curIndex < index){
preNode = current;
current = current.next;
curIndex++;
}
preNode.next = current.next;
this.length--;
console.log('删除成功!');
}
getHead(){
if(this.isEmpty()){
console.log('这是一个空链表!');
return null;
}
return this.head;
}
toString(){
if(this.isEmpty()){
console.log('这是一个空链表!');
return null;
}
let tempNode = this.head;
let str = this.head.value.toString();
while(tempNode.next !== null){
tempNode = tempNode.next;
str = str+' '+tempNode.value.toString();
}
return str;
}
print(){
console.log(this.toString());
}
}
console