单链表(linklist)
单链表 append insert remove get print
节点
- value
- next
class ListNode(value){
constructor{
this.value = value
this.next = null
}
}
链表
- head
- size
class Linklist(){
constructor{
this.head = null
this.size = 0
}
}
append(value)
- 新建节点
- 判断插入位置
- 接收头节点
- 循环
- 赋值
- size++
append(value){
const newNode = new Listnode(value)
if(this.head === null){
this.head = newNode
}else{
let current = this.head
while(current.next !== null){
current = current.next;
}
current.next = newNode;
}
this.size++;
}
insert(index,value)
- 判断index范围
- 新建节点
- 判断插入位置
- 接收头节点
- 循环
- 赋值
- size++
insert(index.value){
if(index < 0 || index > this.size){
throw new Error("index out of range")
}
const newNode = new Listnode(value);
if(index === 0){
newNode.next = this.head;
this.head = newNode;
}else{
let current = this.head;
let i = 0;
while(i < index){
previous = current;
current = current.next;
i++;
}
newNode.next = current;
previous.next = newNode;
}
this.size++;
}
remove(index)
- 判断index范围
- 接收头节点
- 判断插入位置
- 循环
- 赋值
- size–
remove(index){
if(index < 0 || index > this.size){
throw new Error("index out of range")
}
let current = this.head;
if(index === 0){
this.head = current.next
}else{
let previous = null;
let i = 0;
while(i < index){
previous = current;
current = current.next;
i++;
}
previous.next = current.next;
}
this.size --;
return current.value
}
get(index)
- 判断index范围
- 接收头节点
- 循环
- 返回值
get(index){
if(index < 0 || index > this.size){
throw new Error("index out of range")
}
let current = this.head;
let i = 0;
while(i < index){
current = current.next;
i++;
}
return current.value
}
print()
- 接收头节点
- push
- next
- log
print(){
let current = this.head;
let result = [];
while(current.next !== null){
result.push(curremt.value);
current = current.next;
}
console.log(result.join('->'));
}
Written on May 23, 2024