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

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

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

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

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

好處:可以添加或移除任意項(xiàng),它會(huì)按需擴(kuò)容,且不需要移動(dòng)其他元素。

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

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

    鏈表:想要訪問(wèn)鏈表中的一個(gè)元素,需要從起點(diǎn)(表頭)開(kāi)始迭代列表直到找到所需的元素。

做點(diǎn)小筆記。

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)鏈表,直到最后一項(xiàng)
while(current.next){
current = current.next
}
current.next = node
}
length ++ //更新鏈表長(zhǎng)度
}
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 ++ //更新鏈表長(zhǎng)度
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){ //移除第一個(gè)元素
head = current.next
}else{
while(index++ < position){
previous = current
current = current.next
}
previous.next = current.next //移除元素
}
length -- //更新長(zhǎng)度
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)鏈表知識(shí)詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論