用js写单链表和双向链表

主要是理解单链表的结构和原理。

单链表 

 

试验一下:

var l = new list();

l.insert("a","head");

l.insert("b","a");

l.insert("c","b");

l.remove("b");

l.show();

双向链表

function node(Element){

this.Element = Element;

this.next = null;

this.previous = null;

}

function listt(){

this.head = new node("head");

this.find = find;

this.insert = insert;

this.remove = remove;

this.show = show;

}

function find(item){

var current = this.head;

while(current.next!=null && current.Element!=item){

current = current.next;

}

return current;

}

function insert(newElement,item){

var newNode = new node(newElement);

var current = this.find(item);

newNode.next = current.next;

newNode.previous = current;

current.next = newNode;

if(newNode.next!=null){

newNode.next.previous = newNode;

}

}

function remove(item){

var temp = this.find(item);

var current = this.head;

while(current.next!=null && current.next.Element!=item){

current = current.next;

}

current.next = temp.next;

temp.next.previous = current;

}

function show(){

var current = this.head;

while(current.next!=null){

console.log(current.next.Element);

current = current.next;

}

}

 

var li = new listt();

li.insert("1","head");

li.insert("2","1");

li.insert("3","2");

li.insert("4","3");

li.show();

 循环链表

function node(element){

this.element = element;

this.next = null;

}

function list(){

this.head = new node("head");

this.find = find;

this.insert = insert;

this.remove= remove;

this.show= show;

}

function find(item){

var current = this.head;

while(current.next!=current && current.element!=item){

current = current.next;

}

return current;

}

function insert(newElement,item){

var newNode = new node(newElement);

var current = this.find(item);

newNode.next=current.next;

current.next=newNode;

}

function remove(item){

var temp = this.find(item);

var current = this.head;

while(current.next.element!=item){

current = current.next;//还有待完善

}

current.next = temp.next;

}

function show(){

var current = this.head;

while(current.next!=current && current.next!=null){

console.log(current.next.element);

current = current.next;

}

}

var list = new list();

list.insert("1","head");

list.insert("2","1");

list.insert("3","2");

list.insert("4","3");

list.show();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值