什么是单向链表?单向链表的基本操作?如何封装?......
2022/8/25 6:24:18
本文主要是介绍什么是单向链表?单向链表的基本操作?如何封装?......,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
什么是单向链表?
单向链表(单链表)是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始;链表是使用指针进行构造的列表--百度
单向链表的基本操作?
-
append(element)
:向列表尾部添加一个新的项 -
insert(position, element)
:向列表的特定位置插入一个新的项。 -
remove(element)
:从列表中移除一项。 -
indexOf(element)
:返回元素在列表中的索引。如果列表中没有该元素则返回-1
。 -
removeAt(position)
:从列表的特定位置移除一项。 -
isEmpty()
:如果链表中不包含任何元素,返回true
,如果链表长度大于0则返回false
。 -
size()
:返回链表包含的元素个数。与数组的length
属性类似。 -
toString()
:由于列表项使用了Node
类,就需要重写继承自JavaScript对象默认的toString
方法,让其只输出元素的值。
如何封装?
1、向链表最后添加元素
// 节点的结构 class Lnode { constructor(data) { this.data = data; this.next = null; } } // 链表的结构 class LinkList { constructor() { this.head = null; this.length = 0; } append(ele) { // 创建新节点 let newnode = new Lnode(ele); console.log(newnode); if (this.head == null) { this.head = newnode; } else { let current = this.head; while (current.next != null) { // 继续找 current = current.next }; current.next = newnode; } this.length++ } } let list = new LinkList(); for (let i = 0; i < 5; i++) { list.append(i) } console.log(list);
打印:结果
2、链表的insert操作
insert(position, el) { // 位置是否合法 if (position < 0 || position > this.length || Number.isInteger(position)) { return false } let newnode = new Lnode(ele) // 1、在头部插入 if (position == 0) { if (this.head == null) { this.head = newnode; } else { newnode.next = this.head; this.head = newnode } this.length++; } else if (position == this.length) { //尾部 this.append(ele) } else { let current = this.head let index = 0 while (index < position - 1) { current = current.next; index++ } newnode.next = current.next current.next = newnode; this.length++ } }
3、移除指定位置的元素
removeAt(position) { if (position < 0 || position > this.length - 1 || !Number.isInteger(position)) { return false } if (this.head == null) { return }else{ if(position ==0 ){ this.head = this.head.next }else{ let current = this.head, index = 0; index = 0; while (index< position -1){ current = current.next; index++; } current.next = current.next.next; } this.length--; } }
4、查找指定元素的位置,存在返回index
indexOf(ele){ let current = this.head, index =0; while(index<this.length){ if(current.data ==ele){ return index }else{ current = current.next index++; } } return -1; }
5、remove 移除指定元素
remove(ele){ let index = this.indexOf(ele); this.removeAt(index) }
6、将链表中的数据连接为字符串
toString(){ let current = this.head,index = 0,res = ""; while(index <this.length){ res += "-"+current.next; current = current.next; index++; } return res.slice(1) }
这篇关于什么是单向链表?单向链表的基本操作?如何封装?......的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?
- 2024-05-09企业src漏洞挖掘-有意思的命令执行
- 2024-05-08阿里云域名注册流程,分享给第一次购买域名的新手站长!