最近在看《javascript数据结构和算法》这本书,补一下数据结构和算法部分的知识,觉得自己这块是短板。
链表:存储有序的元素集合,但不同于数组,链表中的元素在内存中不是连续放置的。每个元素由一个存储元素本身的节点和一个指向下一个元素的引用(也称指针或链接)组成。
好处:可以添加或移除任意项,它会按需扩容,且不需要移动其他元素。
与数组的区别:
数组:可以直接访问任何位置的任何元素;
链表:想要访问链表中的一个元素,需要从起点(表头)开始迭代列表直到找到所需的元素。
做点小笔记。
function LinkedList(){var Node = function(element){this.element = elementthis.next = null}var length = 0var head = nullthis.append = function(element){var node = new Node(element)var currentif(head == null){ //链表为空head = node}else{ //链表不为空current = head//循环链表,直到最后一项while(current.next){current = current.next}current.next = node}length ++ //更新链表长度}this.insert = function(position,element){var node = new Node(element)var current = headvar previousvar index = 0if(position>=1 && position<=length){ //判断是否越界if(position === 0){ //插入首部node.next = currenthead = node}else{while(index++ < position){previous = currentcurrent = current.next}node.next = currentprevious.next = node}length ++ //更新链表长度return true}else{return false}}this.indexOf = function(element){var current = headvar index = -1while(current){if (element === current.element) {return index}index++current = current.next}return -1}this.removeAt = function(position){if(position>-1 && position<length){ //判断是否越界var current = headvar previousvar index = 0if(position === 0){ //移除第一个元素head = current.next}else{while(index++ < position){previous = currentcurrent = current.next}previous.next = current.next //移除元素}length -- //更新长度return current.element}else{return null}}this.remove = function(element){var index = this.indexOf(element)return this.removeAt(index)}this.isEmpty = function(){return length == 0}this.size = function(){return length}this.toString = function(){var current = headvar string = ""while(current){string = "," + current.elementcurrent = current.next}return string.slice(1)}this.getHead = function(){return head}}
以上所述是小编给大家介绍的JavaScript数据结构链表知识详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!