递归插入双向链表的末尾 [英] Recursively insert at the end of doubly linked list

查看:65
本文介绍了递归插入双向链表的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双向链接列表,我想递归在列表末尾插入一个元素。我现在有一个方法可以做到这一点而无需递归,并且可以正常工作。我似乎无法理解如何使用递归。我认为,在带有递归的单链接列表的末尾插入是很容易理解的,因此,我希望有人可以解释在双链接列表时如何执行此操作。这是我想递归的普通插入方法:

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


推荐答案

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

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

这篇关于递归插入双向链表的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆