//节点对象
class Node{
constructor(data){
this.data=data;//存储节点数据
this.next=null;//存储下一个节点的引用,默认为null
}
}
//链表对象
class LinkedList{
constructor(){
this.head=null;//链表头节点,默认为null
}
//向链表末尾添加节点
append(data){
const newNode=new Node(data)
if(this.head===null){
//如果链表为空,将新节点设置为头节点
this.head=newNode;
}else{
let currentNode=this.head;
//找到节点的末尾
while(currentNode.next!==null){
currentNode=currentNode.next;
}
//在末尾添加新节点
currentNode.next=newNode
}
}
// 打印链表元素
print(){
let currentNode=this.head;
let output='';
while(currentNode!==null){
output+=`${currentNode.data}->`;
currentNode=currentNode.next;
}
output+=`null`
console.log(output)
}
//在指定位置插入节点
insertAt(positon,data){
const newNode=new Node(data);
if(positon===0){
//如果要在头部插入节点
newNode.next=this.head
this.head=newNode;
}else{
let count=0;
let previousNode=null;
let currentNode=this.head;
//找到要插入位置的节点和前一个节点
while(count<positon){
count++;
previousNode=currentNode
currentNode=currentNode.next;
}
//指定位置插入节点
newNode.next=currentNode;
previousNode.next=newNode
}
}
//从链表中删除指定位置的节点
removeAt(positon){
if(this.head===null){
return;//如果链表为空,直接返回
}
let count=0;
let previousNode=null;
let currentNode=this.head;
//找到要删除位置的节点和前一个节点
while(count<positon){
if(currentNode===null){
return;//如果链表长度不足将删除位置,直接返回
}
count++;
previousNode=currentNode;
currentNode=currentNode.next;
}
if(previousNode===null){
//如果要删除的是头节点
this.head=currentNode.next;
}else{
previousNode.next=currentNode.next;
}
}
//获取节点的长度
size(){
let count =0;
let currentNode=this.head;
while(currentNode!==null){
count++;
currentNode=currentNode.next;
}
return count;
}
}
const linkedList = new LinkedList();
linkedList.append(10);
linkedList.append(20);
linkedList.append(30);
linkedList.print(); // 输出: 10 -> 20 -> 30 -> null
linkedList.insertAt(1, 15);
linkedList.print(); // 输出: 10 -> 15 -> 20 -> 30 -> null
linkedList.removeAt(2);
linkedList.print(); // 输出: 10 -> 15 -> 30 -> null
console.log(linkedList.size()); // 输出: 3