前言
上一期学习了线性表,主要是线性表和单向链表,今天主要学习了双向链表
链表
链表分为单向链表、循环链表和双向链表:
- 单向链表:链表中只包含一个指针域。单向链表可由头指针唯一确定。
- 循环链表:循环链表是另一种形式的链式存储结构,他的特点是表种最后一个结点的指针域指向头结点,整个链表形成一个环。循环链表的操作和线性链表基本一致,差别仅在于算法中的循环条件不是
item.next === null
或者item,而是它们是否等于头结点。所以本期没有写一套循环链表的实现。 - 双向链表:以上讨论的链式存储结构的结点中只有一个指示直接后继的指针域,由此,从某个结点出发只能顺指针往后寻查其他结点。若要寻查结点的直接前驱,则需从表头指针出发。为了克服单链表这种单向性的缺点,可以利用双向链表。双向链表的结点中有两个指针域,其一指向直接后继,另一个指向直接前驱。
以下是双向链表的实现
function D_Node(element){
this.element = element;
this.prior = null;
this.next = null;
};
function Double_List() {
this.head = new D_Node("head");
};
Double_List.prototype = {
searchD_Node:function(item){
var cur_D_Node = this.head;
while(cur_D_Node.element !== item ){
cur_D_Node = cur_D_Node.next;
}
return cur_D_Node;
},
searchPriorD_Node:function(item){
var current = this.searchD_Node(item);
return current.prior;
},
searchNextD_Node:function(item){
var current = this.searchD_Node(item);
return current.next;
},
getD_listLenth:function(){
var cur_D_Node = this.head;
var i = 0;
while(!(cur_D_Node.next === null)){
cur_D_Node = cur_D_Node.next;
i++;
}
return i;
},
getElementByIndex:function(index){
var cur_D_Node = this.head;
for(var i = 0; i<index;i++){
cur_D_Node = cur_D_Node.next;
}
return cur_D_Node.element;
},
insert:function(newElement,item){
var newD_Node = new D_Node(newElement);
var item = this.searchD_Node(item);
newD_Node.prior = item;
newD_Node.next = item.next;
item.next = newD_Node;
},
D_NodeDelete:function(item){
var prior_D_Node = this.searchPriorD_Node(item);
var Next_D_Node = this.searchNextD_Node(item);
while(!(prior_D_Node.next === null)){
prior_D_Node.next = prior_D_Node.next.next;
Next_D_Node.prior = Next_D_Node.prior.prior;
return;
}
},
};
后记
最近几天比较忙,量少了一点,过后补上~~