此例是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 {sl.addhead(arguments[i]);
}
alert(未排序的链表);
sl.print();
sl.bubblesort();
alert(已排序的链表 从小到大);
sl.print();
})(1,2,3,4)