欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript數(shù)據(jù)結(jié)構(gòu)鏈表知識詳解

 更新時間:2016年11月21日 08:52:19   作者:小少等等等  
存儲有序的元素集合,但不同于數(shù)組,鏈表中的元素在內(nèi)存中不是連續(xù)放置的。每個元素由一個存儲元素本身的節(jié)點和一個指向下一個元素的引用(也稱指針或鏈接)組成。下面通過本文給大家詳細介紹下,需要的朋友參考下

最近在看《javascript數(shù)據(jù)結(jié)構(gòu)和算法》這本書,補一下數(shù)據(jù)結(jié)構(gòu)和算法部分的知識,覺得自己這塊是短板。

鏈表:存儲有序的元素集合,但不同于數(shù)組,鏈表中的元素在內(nèi)存中不是連續(xù)放置的。每個元素由一個存儲元素本身的節(jié)點和一個指向下一個元素的引用(也稱指針或鏈接)組成。

好處:可以添加或移除任意項,它會按需擴容,且不需要移動其他元素。

與數(shù)組的區(qū)別:

    數(shù)組:可以直接訪問任何位置的任何元素;

    鏈表:想要訪問鏈表中的一個元素,需要從起點(表頭)開始迭代列表直到找到所需的元素。

做點小筆記。

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
//循環(huán)鏈表,直到最后一項
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
}
}

以上所述是小編給大家介紹的JavaScript數(shù)據(jù)結(jié)構(gòu)鏈表知識詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論