java - 递归插入到双向链表的末尾

标签 java recursion insert linked-list doubly-linked-list

我有一个双向链表,我想递归地在列表末尾插入一个元素。我现在有一个无需递归即可完成此操作的方法,并且它有效。我似乎无法理解如何用递归来做到这一点。我认为用递归在单链表的末尾插入是很容易理解的,所以我希望有人能解释当列表是双向链表时如何做到这一点。这是我想要递归的正常插入方法:

public void insert(T element) {
    Node in = new Node(element);

    if (in == null) {
        first = in;
    } else {
        Node tmp = first;
        while (tmp.next != null) {
            tmp = tmp.next;
        }
        tmp.next = in;
        in.prec = tmp;
    }
}

最佳答案

这个想法只是用函数调用重写 while 循环:

public void insert(T element) {
    insert(element, first);    // initialization
}

private void insert(T e, Node n) {
    if(n == null) {            // if the list is empty
        first = new Node(e);
    } else if(n.next == null) {       // same condition as in the while loop
        None newNode = new Node(e);
        n.next = newNode;
        newNode.prec = n;
    } else {
        insert(e, n.next);    // looping
    }
}

关于java - 递归插入到双向链表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29926426/

相关文章:

java - Java 中的谓词搜索

java - 计算 ArrayList 中某个类型的引用数

python - Python 中带递归的乘法函数

python - Python 中的递归回溯——在秤上平衡重量

mysql - 将 User-Agent 字符串的哈希存储在 MySQL 表中 : insert if not exists, 返回 id

mysql - 让重复 key mysql正常工作

java - 用于分析 mp3 的库

list - 使用foldl,编写一个将整数列表转换为整数的函数?

c++ - 在 map 中存储标准 map

java - 在 WebLogic 上设置默认的 CookieManager 没有效果