JavaScript 实现链表数据结构及冒泡排序
作者:拾光时间:2026-10-29 08:02:31浏览:560
本文介绍如何使用 JavaScript 构建基础的链表数据结构,包括节点定义、头插法添加元素及遍历打印功能。在此基础上扩展实现冒泡排序算法,通过交换节点指针完成数据排序,并附带完整的可运行代码示例,展示未排序与排序后的链表状态。
JavaScript 链表数据结构实现
本示例演示了如何使用 JavaScript 构建一个链表数据结构,并在此基础上对链表节点进行排序处理。
该实现基于通用的 GenericList 链表类进行扩展,旨在支持多种排序算法以及节点的增加、删除和修改操作。
具体实现代码如下:
function Node(){
this.data=null;
this.next=null;
}
function GenericList(){
this.head=null;
this.current=null;
//打出所有的链表结点
this.print= function(){
this.current=this.head;
while(this.current!=null){
alert(this.current.data);
this.current=this.current.next;
}
},
//建立链表
this.addHead =function(t){
var node=new Node();
node.data=t;
node.next=this.head;
this.head=node;
}
}
链表冒泡排序算法逻辑function SortList(){
//冒泡排序链表
this.BubbleSort=function()
{
if(this.head==null||this.head.next==null)
{
return ;
}
var swapped;
do{
this.previous=null;
this.current=this.head;
var swapped=false;
while(this.current.next!=null)
{
if(this.current.data-this.current.next.data>0)
{
var tmp=this.current.next;
this.current.next=this.current.next.next;
tmp.next=this.current;
if(this.previous==null)
{
this.head=tmp;
}
else
{
this.previous.next=tmp;
}
this.previous=tmp;
swapped=true;
}
else
{
this.previous=this.current;
this.current=this.current.next;
}
}
}while(swapped);
}
}
SortList.prototype=new GenericList();
排序功能测试与调用示例(function Main(){
var sl=new SortList();
for(var i=0;i<arguments.length;i++)
{sl.addHead(arguments[i]);
}
alert("未排序的链表");
sl.print();
sl.BubbleSort();
alert("已排序的链表 从小到大");
sl.print();
})("1","2","3","4")作者最新文章
JS处理含Emoji或中文的字符串转数组乱码问题
2026-11-05 16:12:28
JS怎么使用展开运算符合并对象
2026-11-05 14:42:18
ES6+环境下判断JS对象为空的简洁写法
2026-11-05 12:12:23
怎么通过replacer函数自定义JS中JSON的格式化输出
2026-11-05 11:19:44
JS正则表达式基础:字面量与RegExp构造函数的区别及常用元字符
2026-11-05 11:16:58
