js实现链表
Posted 把我当做一棵树叭
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js实现链表相关的知识,希望对你有一定的参考价值。
class Node { constructor(elem) { this.elem = elem; this.next = null; } } class LinkedList { constructor() { this.head = null; this.length = 0; } // 末尾加入 append(element) { let node = new Node(element); if (this.head) { let current = this.head; while (current.next) { current = current.next; } current.next = node; } else { this.head = node; } this.length++; } // 插入 未考虑position超出长度 insert(position, element) { let node = new Node(element); let index = 0; let current = this.head; let previous = null; if (position === 0) { if (this.head) { this.head = node; node.next = current; } else { this.head = node; } } else { while (index++ < position) { previous = current; current = current.next; } previous.next = node; node.next = current; } this.length++; } // 移除 remove(position) { let current = this.head; if (position === 0) { if (this.head) { } else { } } } }
以上是关于js实现链表的主要内容,如果未能解决你的问题,请参考以下文章
NC41 最长无重复子数组/NC133链表的奇偶重排/NC116把数字翻译成字符串/NC135 股票交易的最大收益/NC126换钱的最少货币数/NC45实现二叉树先序,中序和后序遍历(递归)(代码片段
817. Linked List Components - LeetCode