JS ES6 单链表2种插入尾部方式

文章介绍了两种在单链表中添加元素的方法,一种是在尾部插入时使用尾指针,另一种是遍历到尾部再插入。类定义包括节点结构和链表结构,提供了插入和判断链表是否为空的功能,并展示了实际插入操作的示例。

 一种是类里加一个指向尾部最后一个元素指针。通过他添加一个元素到队列最后。

一种是每次增一个元素都从头开始遍历直到最后一个,然后添加。打开出来有单链表结构是一样的。除了上面的 多了一个队尾指针。

class Node {
    //单个结点
    data;
    next;

    constructor(value) {
        this.data = value;
        this.next = null;
    }
}

//单链表
class LinkList {
    head;/* 第一个元素*/
    length = 0; //链表长度
    tail;

    //判断链表是否为空
    isEmpty() {
        return this.length === 0;
    }

    constructor(node = null) {
        this.head = node; /*链表头*/
        this.tail = node

    }

    /**
     *  尾部插入数据
     * @param {*} ele
     */
    append(ele) {
        let newNode = new Node(ele);
        let currentNode;
        if (this.head === null) {
            this.head = newNode;
        } else {
            currentNode = this.head;
            while (currentNode.next) {
                currentNode = currentNode.next;
            }
            currentNode.next = newNode;
            this.tail = newNode;
        }
        this.length++;
    }

    //尾部插入元素
    insert(data) {
        let newNode = new Node(data);
        if (this.head === null) {
            this.head = newNode;
            this.tail = newNode;
        } else {
            this.tail.next = newNode;
            this.tail = newNode;
            // this.tail=
        }
        this.length++
        return this;
    }

    toString() {
        let nodes = [];
        let current = this.head;
        while (current) {
            nodes.push(current.data);
            current = current.next;
        }
        return nodes.join(",")
    }
}

function newLinklist() {
    let linklist = new LinkList();
    // console.log(linklist)
    linklist.insert(4);

    linklist.insert(15);
    linklist.insert(6);
    linklist.insert(7);
    console.log(linklist.toString())
    console.log(linklist.length)
    console.log(linklist.head.data)
    return linklist;
// console.log(linklist.tail.data)
}

function newLinklist2() {
    let linklist = new LinkList();
    // console.log(linklist)
    linklist.append(4);
    linklist.append(15);
    linklist.append(6);
    linklist.append(7);
    console.log(linklist.toString())
    console.log(linklist.length)
    console.log(linklist.head.data)
    console.log(linklist.tail.data)
    return linklist;
}

let l1 = newLinklist()
let l2 = newLinklist2()
console.log(l1, l2)

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值