本文實例講述了JavaScript數據結構之雙向鏈表定義與使用方法。分享給大家供大家參考,具體如下:
雙向鏈表和普通鏈表的區別在于,在鏈表中,一個節點只有鏈向下一個節點的鏈接,而在雙向鏈表中,鏈接是雙向的:一個鏈向下一個元素,另一個鏈向前一個元素。
雙向鏈表提供了兩種迭代列表的方法:從頭到尾,或者反過來。我們也可以訪問一個特定節點的下一個或前一個元素。在單向鏈表中,如果迭代列表時錯過了要找的元素,就需要回到列表起點,重新開始迭代。這是雙向鏈表的一個優點。
function DoubleLink(){
var length=0;//鏈表長度
var head=null;//頭結點的引用
var tail=null;//尾節點的引用
function Node(e){
this.element=e;
this.next=null;
this.previous=null;
}
this.insertAt=function(position,e){//在任意位置添加節點
if(position>=0&&position<=length){//判斷邊界
var node=new Node(e);
var current=head;
var previous;
var index=0;
if(position==0){//在第一個位置添加
if(!head){//鏈表為空的時候添加第一個節點
head=node;
tail=node;
}else{
current=head;
node.next=current;
current.previous=node;
head=node;
}
}else if(position==length){//在鏈表末尾添加
current=tail;
current.next=node;
node.previous=current;
tail=node;
}else{
while(index<position){
previous=current;
current=current.next;
index++;
}
previous.next=node;
node.previous=previous;
node.next=current;
current.previous=node;
}
length++;
return true;
}else{
return null;
}
}
this.removeAt=function(position){//刪除任意位置的節點
if(position>-1&&position<length){//邊界判斷
var current=head;
var previous;
var index=0;
if(position==0){//刪除第一個位置的節點
head=current.next;
if(length==1){//如果只有一項
tail=null;
}else{
head.previous=null;
}
}else if(position==length-1){//刪除最后一項
current=tail;
tail=current.previous;
tail.next=null;
}else{
while(index<position){
previous=current;
current=current.next;
index++;
}
previous.next=current.next;
current.next.previous=previous;
}
length--;
return current.element;
}else{
return null;
}
}
this.indexOf=function(e){//獲取節點位置,從頭開始數
var current=head;
var index=0;
while(current){
if(current.element==e){
return index;
}
current=current.next;
index++;
if(index>=length)return null;
}
}
this.isEmpty=function(){//判斷鏈表是否為空
return length==0;
}
this.mylength=function(){//鏈表長度
return length;
}
this.print1=function(){//從頭到尾打印鏈表
var current=head;
while(current){
console.log(current.element);
current=current.next;
}
}
this.print2=function(){//從尾到頭打印鏈表
var current=tail;
while(current){
console.log(current.element);
current=current.previous;
}
}
this.getHead=function(){//獲取頭節點
return head;
}
this.getTail=function(){//獲取尾節點
return tail;
}
}
var link=new DoubleLink();//實例化一個對象
link.insertAt(0,'d');
link.insertAt(1,'e');
link.insertAt(2,'f');
link.insertAt(3,'g');
link.insertAt(4,'h');
link.insertAt(5,'i');
link.insertAt(6,'j');
link.insertAt(7,'k');
link.removeAt(7);
link.removeAt(0);
link.print1();//efghij
link.print2();//jihgfe
console.log(link.getHead());//e
console.log(link.getTail());//j
console.log(link.indexOf('f'));//1
運行結果:

更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript數據結構與算法技巧總結》、《JavaScript數學運算用法總結》、《JavaScript排序算法總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript查找算法技巧總結》及《JavaScript錯誤與調試技巧總結》
希望本文所述對大家JavaScript程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。