递归获取带有索引的双端队列的值

时间:2018-12-14 05:54:32

标签: java

我正在构建一个圆形哨兵双端队列,我想在不更改列表的情况下获得一个值。

public class LinkedListDeque<Generic> {
    private GenericNode sentinel;
    private int size;
    private class GenericNode{
        public Generic item;
        public GenericNode next;
        public GenericNode prev;

    public GenericNode(GenericNode p, Generic i, GenericNode n) {
        item = i;
        next = n;
        prev = p;
     }
    }

    public LinkedListDeque() {
        sentinel = new GenericNode(null, null, null);
        sentinel.next = sentinel;
        sentinel.prev = sentinel;
        size = 0;
    }
    public LinkedListDeque(Generic x) {
        sentinel = new GenericNode(null, null, null);
        sentinel.next = new GenericNode(sentinel, x, sentinel);
        sentinel.prev = sentinel.next;
        size = 1;
public Generic getRecursive(int r) {
        if (r == 0) {
            return sentinel.next.item;
        } else {
            sentinel.next = sentinel.next.next;
            return getRecursive(r-1); //fix this
        }
    }

此方法有效,但它也会更改我不想要的列表。当我尝试

this.next.getRecursive(r-1)

它抛出一个错误。我不知道如何引用它,因为前哨似乎使我失望。

1 个答案:

答案 0 :(得分:1)

如果您不想修改状态,则需要传递一个参考节点,例如:

public Generic getRecursive(int r) {
    return getRecursive(r, sentinel);
}

private static Generic getRecursive(int r, GenericNode node) {
    if (r == 0) {
        return node.item;
    }
    return getRecursive(r - 1, node.next);
}