Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

java - 在Java中使用单个堆栈实现队列(Implementing Queue Using single stack in java)

I'm trying to implement a queue using single stack using recursion.

(我正在尝试使用递归使用单个堆栈实现队列。)

But I am struggling to implement the deQueue() method.

(但是我在努力实现deQueue()方法。)

This method has to return the first inserted element in the queue which is nothing but the last element in stack.

(此方法必须返回队列中的第一个插入元素,而该元素只是堆栈中的最后一个元素。)

The below code is not working for me.

(以下代码对我不起作用。)

Please correct it and share.

(请更正并分享。)

public String deQueue() {       
    return recursive();
}

public String recursive() {
    String result1 = null;
    String data;
    if (stack.empty()) {
         return null;
    }

    if (stack.count() ==1) {
        result1 = stack.pop();
        return result1;
    }

    data = stack.pop();
    recursive();
    stack.push(data);

    return result1;
}
  ask by Naveen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your problem is, that you ignore the result of recursive().

(您的问题是,您忽略了recursive()的结果。)

...
data = stack.pop();
result1 = recursive();
stack.push(data);
... 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...