JavaScript单链表的遍历和插入
单链表是一种非顺序非连续的数据结构,由若干节点组成,每个节点有value值和指向下一个node的next指针,具体地:
单链表:
class SLinkList { constructor() { this.size = 0 this.head = null //头节点 } }
node节点:
class Node { constructor(value) { this.value = value this.next = null } }
查找链表中某个位置的节点:
find(pos){ let node= this.head while((pos--) && node.next){ node = node.next } return node }
实现向链表中pos位置后添加数据:
append(value, pos){ if (this.size) { const findNode = this.find(pos) const insertNode = new Node(value) insertNode.next = findNode.next findNode.next = insertNode } else { this.head = new Node(value) } this.size ++ }
遍历链表:
traversal(callback) { let currentNode = this.head while (currentNode) { callback(currentNode.value) currentNode = currentNode.next } }
完整的SLinkList代码:
class SLinkList { constructor() { this.size = 0 this.head = null //头节点 } find(pos){ let node = this.head while((pos--) && node.next){ node = node.next } return node } append(value, pos){ if (this.size) { const findNode = this.find(pos) const insertNode = new Node(value) insertNode.next = findNode.next findNode.next = insertNode } else { this.head = new Node(value) } this.size++ } traversal(callback) { let currentNode = this.head while (currentNode) { callback(currentNode.value) currentNode = currentNode.next } } }
调用:
const list = new SLinkList() list.append('a1') list.append('b1', 1) list.append('c1', 2) list.append('d1', 3) list.append('e1', 4) list.append('f2', 2) list.append('g2', 3) list.traversal(console.log) 输出结果: a1 b1 c1 f2 g2 d1 e1
JavaScript
网站开发
小程序开发
阅读排行
-
1. 微信支付商户申请接入流程
微信支付,是微信向有出售物品/提供服务需求的商家提供推广销售、支付收款、经营分析的整套解决方案,包括多种支付方式,如JSAPI支付、小程序支付、APP支付H5支付等支付方式接入。
查看详情 -
2. 微信小程序申请注册流程
微信小程序注册流程与微信公众号较为相似,同时微信小程序支持通过已认证的微信公众号进行注册申请,无需进行单独认证即可使用,同一个已认证微信公众号可同时绑定注册多个小程序。
查看详情 -
3. 阿里云域名ICP网络备案流程
根据《互联网信息服务管理办法》以及《非经营性互联网信息服务备案管理办法》,国家对非经营性互联网信息服务实行备案制度,对经营性互联网信息服务实行许可制度。
查看详情 -
4. 浙江省同区域公司地址变更详细流程
提前准备好所有需要的资料,包含:房屋租赁合同、房产证、营业执照正副本、代理人身份证正反面、承诺书(由于我们公司其中一区域已有注册另外一公司,所以必须需要承诺书)
查看详情 -
5. 不容错过!顶级WebSocket封装库:支持断网自动重连与智能心跳检测!
这篇文章精心封装了weboskcet(注:可能是websocket的拼写错误),它卓越地实现了断网重连与自动心跳机制的功能,确保了网络通信的稳定性和实时性。同时,这款封装完全遵循原生websocket的编程规范,用户无需承担任何额外的学习负担,即可轻松上手并投入使用。
查看详情