Recursively insert at the end of doubly linked list

橙三吉。 提交于 2019-12-12 06:15:26

问题


I have a doubly linked list, and I want to insert an element at the end of the list recursively. I have a method now that does this without recursion, and it works. I just can't seem to understand how to do it with recursion. Inserting at the end of a singly linked list with recursion is quite easy to understand I think, so I hope that someone can explain how to it do it when the list is doubly linked. Here is my normal insertion method that I want to make recursive:

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;
    }
}

回答1:


The idea is just to re-write the while loop with a function call:

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
    }
}


来源:https://stackoverflow.com/questions/29926426/recursively-insert-at-the-end-of-doubly-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!