链表
单链表的操作
本文主要讲一下单链表的基本操作的实现思路,以及一种实现方式(也可以通过其他方式,例如删除的时候可以根据值删除也可以根据位置删除)
单链表的插入
单链表的插入需要知道插入位置的前驱,先让新节点(newNode)的next指向前驱节点(p)的next,然后改变前驱节点(p)的next,使它指向新的节点(newNode)
「注意:这个顺序是不可改变的,否则p节点的之后的节点会全部丢失,造成链表断链」
![a450811e851cdde4f15f99546c5200ab.png](https://i-blog.csdnimg.cn/blog_migrate/8b6aac9cc177b67906c51f248e5b17d8.png)
![e007ae92ee0bae2a7519bc663f7b0c4f.png](https://i-blog.csdnimg.cn/blog_migrate/e4323bcb98c32714f65940a95e6193b1.png)
//在pos之后插入一个节点
insertAtPosition(value,pos){
let newNode = new Node(value)
if(this.head === null){
return false
}
let i = 0
let p = this.head
while(p !== null){
if(i !== pos){
i++
p = p.next
}else{
newNode.next = p.next
p.next = newNode
return true
}
}
return false
}
单链表的删除
单链表的删除同样需要知道插入位置的前驱,把前驱节点(p)的next指向被删除节点(delNode)的next,如果这个链表只有一个节点,就把head改为null
![7c297eafb41fa92f8fbacb4c3fb66999.png](https://i-blog.csdnimg.cn/blog_migrate/1e5bd34b275e90df6a37ab693f705d65.png)
![75c6e5020c8fd92ce52b31a10b175e70.png](https://i-blog.csdnimg.cn/blog_migrate/87e706768aa0a216bef2963547d3a98a.png)
![0b00b64e7fd96ab45016106304ede714.png](https://i-blog.csdnimg.cn/blog_migrate/aef87def94260464d52d2e9c94a7414e.png)
//在pos位置删除一个节点
deleteAtPosition(pos){
if(this.head === null){
return false
}
let i = 0
if(pos === 0){
this.head = this.head.next
return true
}
let p = this.head
while(p !== null){
if(i !== pos - 1){
i++
p = p.next
}else{
let delNode = p.next
p.next = delNode.next
return true
}
}
return false
}
单链表的遍历
我们以打印单链表为例子来简单介绍一下单链表的遍历,单链表的遍历思路是用一个遍历指针(p),只要遍历指针不空,就打印他的key,然后让遍历指针走向下一个节点
![7298a8b42effd552af7ea58e707c3009.png](https://i-blog.csdnimg.cn/blog_migrate/0d79db628d4a135433537d6fbc9ae396.png)
![e37c8ce9e3f79e2afecf8ac618079da1.png](https://i-blog.csdnimg.cn/blog_migrate/0cf28536671940c1fa1c6c4a133e8265.png)
printList(){
if(this.head === null){
console.log(`List is empty`)
return false
}
let p = this.head
while(p !== null){
console.log(p.key)
p = p.next
}
}
单链表的查找
在单链表的查找中我们以值查找,我们去遍历链表,然后如果链表节点的val与所要查找的值相等,就返回节点
findInList(value){
if(this.head === null){
return false
}
let p = this.head
while(p !== null){
if(p.val === value){
return p
}else{
p = p.next
}
}
return false
}
Mindset
读者在实现单链表的过程中,可以通过画图来理清链表节点指针之间的关系,这样可以更好的理清思路
单链表的基本操作我们就介绍到这里 还有其他操作可以通过画图的方式一一实现 GoodBye