现在的位置: 首页 > 综合 > 正文

JS实现单链表

2013年05月25日 ⁄ 综合 ⁄ 共 876字 ⁄ 字号 评论关闭
        
        <script> 
            //Student节点
            function Student(no,name){ 
                this.id=no; 
                this.name=name; 
                this.scores={chinese:0,math:0,english:0}; 
            }
             
           //链表
            function List(){ 
                this.head=null; 
                this.end=null; 
                this.curr=null; 
            } 

            //添加节点
            List.prototype.add=function(o){ 
                var tem={ob:o,next:null};
                
                if(this.head){ //链表不为空 
                    this.end.next=tem; 
                    this.end=tem; 
                }
                else{ //链表为空
                    this.head=tem; 
                    this.end=tem; 
                    this.curr=tem; 
                } 
            } 

            //删除第inde个节点
            List.prototype.del=function(inde){ 
                var n=this.head; 
                for(var i=0;i<inde;i++){ 
                    n=n.next; 
                } 
                n.next=n.next.next?n.next.next:null; 
            } 

            //下一个节点
            List.prototype.next=function(){ 
                var te=null; 
                if(this.curr){ 
                    te=this.curr.ob; this.curr=this.curr.next;
                } 
                return te; 
            } 

            //是否存在下一个节点
            List.prototype.hasnext=function(){ 
                if(this.curr.ob!=null)
                    return true; 
                return false; 
            } 
            
            var list=new List(); 
    
            for(var i=0;i<1000;i++){ 
                list.add(new Student(i,'name'+i)); 
            } 
            var i=0; 
            while(list.hasnext()){ 
                document.writeln(list.next().name); 
                if(i==10){
                    document.writeln('<br/>'); 
                    i=0;
                } 
                i++; 
            } 
        </script>

 

抱歉!评论已关闭.