JS实现双向链表添加元素

声明元素及链表

function Node(element){
    this.element = element;//值
    this.next = null;//尾部
    this.prev = null;//头部
}
function DoublyLinkedList(){
    let length = 0;
    let head = null;//连接前一项
    let tail = null;//连接后一项
    //方法
    this.append = append;  //向链表尾部添加元素
    this.insert = insert;  //向链表特定位置插入元素
}

向链表尾部添加元素

function append(element){
    let node = new Node(element);
    let current;
    if(this.head == null){   //为空链表时,把head和tail都指向这个新节点
        this.head = node;
        this.tail = node;
    }else{
        current = this.tail;  //获取最后一项
        current.next = node;  //在最后一项后添加
        node.prev = current;  //连接头部
        this.tail = node;  //更新最后一个节点  
    }
    length++;
}

向链表特定位置插入元素

function insert(position, element){
    if(position < 0 || position > length){//检查越界值
        return false;
    }
    let node = new Node(element);
    let current = this.head;
    let index = 0;
    let previous;
    if(position == 0){  //在第一个位置添加
        if(!this.head){   //空列表情况
            this.head = node;
            this.tail = node;   
        }else{
            node.next = current;
            current.prev = node;
            this.head = node;
        }
    }else if(position == length){//添加到尾部时
        current = this.tail;
        current.next = node;
        node.prev = current;
        this.tail = node;   
    }else{
        while(index++ < position){
            previous = current;
            current = current.next;//找出要插入的位置
        }
        node.next = current;
        current.prev = node;
        previous.next = node;
        node.prev = previous;
    }
    length++;
    return true;
}

验证代码同上一篇

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值