javascript
用javascript模仿java實現的有序鏈表,實現按對象的某個屬性對對象進行排序。
<script>
function Link1(){}
Link1.prototype.obj=null;
Link1.prototype.next1=new Link1();
function Link1.prototype.Link1(object){
obj=object;
}
function SortedList(){}
SortedList.prototype.first=new Link1();
function SortedList.prototype.SortedList(linkArr,nm){
var sortedList=new SortedList();
sortedList.first=null;
for(j=0;j<linkArr.length;j++){
sortedList.insert(linkArr[j],nm);
}
}
var f=new SortedList();
function SortedList.prototype.insert(lnk,nm){
var previous1=null;
var current1=f.first;
while(current1.obj!=null&&lnk.obj[nm]>current1.obj[nm]){
previous1=current1;
current1=current1.next1;
}
if(previous1==null){
f.first=lnk;
}else{
privious1=new Link1();
previous1.next1=lnk;
}
lnk.next1=current1;
}
function SortedList.prototype.remove(lnk){
var temp=new Link1();
temp=f.first;
f.first=f.first.next1;
return temp;
}
function ObjTemp(){}
ObjTemp.prototype.num=0;
ObjTemp.prototype.s="";
var objArr=new Array();
objArr[0]=new Link1();
objArr[0].obj=new ObjTemp();
objArr[0].obj.num=1;
objArr[0].obj.s="第一個";
objArr[1]=new Link1();
objArr[1].obj=new ObjTemp();
objArr[1].obj.num=10;
objArr[1].obj.s="第二個";
objArr[2]=new Link1();
objArr[2].obj=new ObjTemp();
objArr[2].obj.num=9;
objArr[2].obj.s="第三個";
objArr[3]=new Link1();
objArr[3].obj=new ObjTemp();
objArr[3].obj.num=19;
objArr[3].obj.s="第四個";
var slist=new SortedList();
slist.SortedList(objArr,"num");
var psh=new Array();
for(i=0;i<4;i++){
psh[i]=slist.remove();
alert(psh[i].obj.num+psh[i].obj.s+"---PSH");
}
</script>