【问题标题】:Recursively insert at the end of doubly linked list在双向链表的末尾递归插入
【发布时间】:2015-07-07 17:13:00
【问题描述】:

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

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

【问题讨论】:

  • 通常,双向链表对最后一个元素有一个标记,因此在末尾插入既不需要循环也不需要递归。

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


【解决方案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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多