7、双向链表

var log = console.log;

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

function LList(){
	this.head = new Node("head");
	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){
	var currNode = this.head;
	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{
		currNode = this.head;
	}
	return currNode;
}

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

function findLast(){
	var currNode = this.head;
	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 = "";
	var currNode = this.head;
	currNode = this.findLast();
	while(currNode.previous != null){
		str += currNode.element + " ";
		// log(currNode.element);
		currNode = currNode.previous;
	}
	log(str);
}

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

var words = new LList();
words.insert("Late", "head");
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值