Javascript实现的单链表

今天无聊看了看大二的数据结构的书,于是用熟悉的js来写了个单链表,代码如下:

window.onload = function(){
    var listArr = [0,1,2,3,4,5];
    var list = new LinkList();
    for (var i = 0; i < listArr.length; i++) {
        list.insert(listArr[i]);
     };
    list.print();
};
function Node(data){   //节点类
    this.next = null;
    this.data = data;
}
function LinkList(){   //单链表类
    this.head = null;  //头节点
    this.size = 0;     //链表长度
    this.insert = function(data,pos){  //插入方法
        var newNode = new Node(data);
        var tempNode = this.head;
        if (this.head == null) {
            this.head = newNode;
            this.size += 1;
            return newNode;
        }
        if (pos != undefined){
            if(pos > this.size || pos < 1) return null;
            var n = 1;
            while(n < pos-1){
                tempNode = tempNode.next;
                n++;
            }
            newNode.next = tempNode.next;
            tempNode.next = newNode;
            this.size += 1;
            return newNode;
        }else{
            while(tempNode.next != null){
                tempNode = tempNode.next;
            }
            tempNode.next = newNode;
            this.size += 1;
            return newNode;
        }
        return null;
    };
    this.delNode = function(pos){  //删除节点方法
        if(pos > this.size || pos < 1) return false;
        var tempNode = this.head , n = 1;
        this.size -= 1;
        if(pos == 1){
            this.head = tempNode.next;
            return true;
        }
        while(n < pos-1){
            tempNode = tempNode.next;
            n++;
        }
        tempNode.next = tempNode.next.next; 
        return true;
    };
    this.getData = function(pos){   //获取节点方法
        if(pos > this.size || pos < 1) return null;
        var tempNode = this.head , n = 1;
        while(n < pos){
            tempNode = tempNode.next;
            n++;
        }
        return tempNode.data;
    };
    this.print = function(){   //打印所有节点数据的方法
        var tempNode = this.head;
        document.write("The size of the LinkList is " + this.size +"
"); while(tempNode != null){ document.write(tempNode.data + "
"); tempNode = tempNode.next; } } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值