首页 > 解决方案 > 带递归的链表

问题描述

早上好,我正在学习,我想用递归函数制作一个链表,我一直在寻找示例,但我只找到了 Java 或其他类型的示例。从我所看到的情况来看,我想它会是这样的,但我无法让它工作。如果有人可以帮助我,我将不胜感激。谢谢你。


function ListRecurse () {
    this.head = null;
    this.size = 0;
}
function Node () {
    this.data = data; 
    this.next = next;
}
ListRecurse.prototype.add = function (data) {
    let NewNode = new Node(this.add(data), null)
    if (this.head === null) {
        this.head = NewNode;
    }
    else {
        let current = this.head;
        while (current.next) {
            current = current.next;
        }
        current = NewNode
    }
    this.size ++;
}

标签: javascriptrecursionlinked-list

解决方案


您可以利用存储最后一个节点并返回this以获得流畅的界面

function ListRecurse() {
    this.head = null;
    this.last = null;
    this.size = 0;
}

function Node(data, next) {
    this.data = data;
    this.next = next;
}

ListRecurse.prototype.add = function(data) {
    const node = new Node(data, null);
    if (this.head === null) this.head = node;
    else this.last.next = node;
    this.last = node;  
    this.size++;
    return this;
}

const list = new ListRecurse().add(1).add(2).add(3);

console.log(list);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读