递归插入双向链表的末尾

时间:2015-04-28 17:46:14

标签: 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;
    }
}

1 个答案:

答案 0 :(得分:1)

这个想法只是用函数调用重写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
    }
}
相关问题