js 单链表

来源:互联网 发布:用友软件固定资产报废 编辑:程序博客网 时间:2024/06/16 20:48

用JavaScript只用过数组,没有写过别的数据结构,今天练习了一下一个简单的单链表。

    var Node =  function(value){        this.value = value;        this.next = null;    }    var myList =  function(){        this.head = new Node(null);    //设头结点为空        this.insert = function(value){    //插入节点            var p = this.head;            while(p.next!=null){                p = p.next;            }            p.next = new Node(value);        }        this.print = function(){    //打印节点            var p = this.head;            while(p.next!=null){                p = p.next;                document.write(p.value+" ");            }        }        this.findNode = function(position){    //寻找某个位置的节点            if(position<0) return;            var p = this.head;            var i = 0;            while(p.next!=null && i<position){                i++;                p = p.next;            }            return p;    //若position大于链表长度返回最后一个        }        this.remove = function(position){    //移除第position个节点            this.findNode(position-1).next=this.findNode(position).next;        }        this.length=function(){    //链表长度            var len = 0;            var p = this.head;            while(p.next!=null){                len++;                p = p.next;            }            document.write(len);        }    }    var list = new myList();    list.insert("a");    list.insert("b");    list.insert("c");    list.insert("d");    list.print();    //a b c d    list.remove(2);        list.print();    //a c d    list.length();    //3
0 0