单链表
<script>
//单链表
function Node(element) {
this.element=element;
this.next=null;
}
function LList() {
this.head=new Node("head");
this.find=find;
this.insert=insert;
this.display=display;
this.remove=remove;
this.findPrevious=findPrevious;
}
function find(item) {
var currNode=this.head;
while(currNode && (currNode.element!=item)){
currNode=currNode.next;
}
if(currNode){
return currNode;
}else{
var currNode2=this.head;
while(currNode2.next){
currNode2=currNode2.next;
}
return currNode2;
}
}
function findPrevious(item) {
var currNode=this.head;
while(currNode.next && currNode.next.element!=item){
currNode=currNode.next;
}
if(currNode.next){
return currNode;
}else{
return false;//没有找到
}
}
function insert(newElement,item){
var newNode=new Node(newElement);
var pos=this.find(item);
newNode.next=pos.next;
pos.next=newNode;
}
function remove(item) {
var prevNode=this.findPrevious(item);
if(prevNode){
prevNode.next=prevNode.next.next;
}
}
function display() {
var currNode=this.head;
while(currNode.next!=null){
console.log(currNode.next.element);
currNode=currNode.next;
}
}
//测试
var myList=new LList();
myList.insert("aa","head"); //如果没找到要插入的位置,则插入到最后
myList.insert("bb","aa");
myList.insert("cc","bb");
myList.display();
myList.remove("cc");
console.log("删除后:");
myList.display();
</script>
结果如下:

双向链表
<script>
//双向链表
function DouNode(element) {
this.element=element;
this.next=null;
this.previous=null;
}
function DouLList() {
this.head=new DouNode("head");
this.find=find;
this.insert=insert;
this.display=display;
this.findLast=findLast;
this.dispReverse=dispReverse;
}
function dispReverse() {
var currNode=this.findLast();
while(currNode.previous!=null){
console.log(currNode.element);
currNode=currNode.previous;
}
}
function findLast() {
var currNode=this.head;
while(currNode.next!=null){
currNode=currNode.next;
}
return currNode;
}
function display(){
var currNode=this.head;
while(currNode.next!=null){
console.log(currNode.next.element);
currNode=currNode.next;
}
}
function find(item) {
var currNode=this.head;
while(currNode && (currNode.element!=item)){
currNode=currNode.next;
}
if(currNode){
return currNode;
}else{
return this.findLast(); //如果没有找到,则在最后一个位置插入
}
}
function insert(element,item) {
var pos=this.find(item);
var newNode=new DouNode(element);
//在最后一个位置插入和在其他位置插入不同,因为最后一个位置的后继为null
if(pos===this.findLast()){
pos.next=newNode;
newNode.previous=pos;
}else{
newNode.next=pos.next;
newNode.previous=pos;
pos.next.previous=newNode;
pos.next=newNode;
}
}
var myDouLList=new DouLList();
myDouLList.insert("aaa","head");
myDouLList.insert("bbb","aaa");
myDouLList.insert("ccc","bbb");
myDouLList.display();
</script>
结果如下:

本文详细介绍了单链表和双向链表的数据结构实现,包括节点的创建、查找、插入、显示和删除等操作,并通过具体示例展示了如何在JavaScript中实现这两种链表。
&spm=1001.2101.3001.5002&articleId=82973874&d=1&t=3&u=5815878e0ee643b8b18ea0173356c054)
478

被折叠的 条评论
为什么被折叠?



