最近在看《javascript資料結構與演算法》這本書,補一下資料結構和演算法部分的知識,覺得自己這塊是短板。
鍊錶:儲存有序的元素集合,但不同於數組,鍊錶中的元素在記憶體中不是連續放置的。每個元素由一個儲存元素本身的節點和一個指向下一個元素的參考(也稱為指標或連結)組成。
好處:可以添加或移除任意項,它會按需擴容,且不需要移動其他元素。
與陣列的區別:
陣列:可以直接存取任何位置的任何元素;
鍊錶:想要存取鍊錶中的一個元素,需要從起點開始(表頭)開始迭代列表的元素。
做點小筆記。
function LinkedList(){ var Node = function(element){ this.element = element this.next = null } var length = 0 var head = null this.append = function(element){ var node = new Node(element) var current if(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 = head var previous var index = 0 if(position>=1 && position<=length){ //判断是否越界 if(position === 0){ //插入首部 node.next = current head = node }else{ while(index++ < position){ previous = current current = current.next } node.next = current previous.next = node } length ++ //更新链表长度 return true }else{ return false } } this.indexOf = function(element){ var current = head var index = -1 while(current){ if (element === current.element) { return index } index++ current = current.next } return -1 } this.removeAt = function(position){ if(position>-1 && position<length){ //判断是否越界 var current = head var previous var index = 0 if(position === 0){ //移除第一个元素 head = current.next }else{ while(index++ < position){ previous = current current = 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 = head var string = "" while(current){ string = "," + current.element current = current.next } return string.slice(1) } this.getHead = function(){ return head } }