# 7、双向链表

91人阅读 评论(0)

var log = console.log;

function Node(element){
this.element = element;
this.next = null;
this.previous = null;
}

function LList(){
this.find = find;
this.findLast = findLast;
this.insert = insert;
this.remove = remove;
this.findPrevious = findPrevious;
this.findNext = findNext;
this.display = display;
this.dispReverse = dispReverse;
}

function find(item){
while(currNode.element != item){
currNode = currNode.next;
}
return currNode;
}

function findPrevious(item){
var currNode = this.find(item);
if(currNode.previous != null){
currNode = currNode.previous;
}else{
}
return currNode;
}

function findNext(item){
var currNode = this.find(item);
if(currNode.next != null){
currNode = currNode.next;
}else{
}
return currNode;
}

function findLast(){
while(currNode.next != null){
currNode = currNode.next;
}
return currNode;
}

function insert(newElement, item){
var newNode = new Node(newElement);
var current = this.find(item);
newNode.next = current.next;
newNode.previous = current;
current.next = newNode;
}

function remove(item){
var currNode = this.find(item);
if(currNode.next != null){
currNode.previous.next = currNode.next;
currNode.next.previous = currNode.previous;
currNode.next = null;
currNode.previous = null;
}
}

// 反向输出
function dispReverse(){
var str = "";
currNode = this.findLast();
while(currNode.previous != null){
str += currNode.element + " ";
// log(currNode.element);
currNode = currNode.previous;
}
log(str);
}

function display(){
var str = "";
while(currNode.next != null){
str += currNode.next.element + " ";
// log(currNode.next.element);
currNode = currNode.next;
}
log(str);
}

var words = new LList();
words.insert("in", "Late");
words.insert("autumn", "in");
words.insert("winner", "autumn");
words.display();
log("-----");

log("//删除 'autumn'");
words.remove("autumn");
words.display();

log("-----");
log("//在 'in' 后插入 'phaser'");
words.insert("phaser", "in");
words.display();

log("-----");
log("//反向输出");
words.dispReverse();

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：24424次
• 积分：960
• 等级：
• 排名：千里之外
• 原创：64篇
• 转载：12篇
• 译文：0篇
• 评论：1条
最新评论