package q;
import java.util.*;
class GFG
{
static class Queue
{
static Stack<Integer> s1 = new Stack<Integer>();
static Stack<Integer> s2 = new Stack<Integer>();
static void Q(int x)
{
while (!s1.isEmpty())
{
s2.push(s1.pop());
}
s1.push(x);
while (!s2.isEmpty())
{
s1.push(s2.pop());
}
}
static int dQ()
{
if (s1.isEmpty())
{
System.out.println("Q is Empty");
System.exit(0);
}
int x = s1.peek();
s1.pop();
return x;
}
}
public static void main(String[] args) {
Queue q = new Queue();
q.Q(100);
q.Q(200);
q.Q(300);
System.out.println(q.dQ());
System.out.println(q.dQ());
System.out.println(q.dQ());
}
}我正在做一个任务,它需要使用两个堆栈来构建一个队列。我已经做到了,但我有一个问题。如何使用循环打印值而不是逐行打印值?由于某些原因,它不能工作。我试着写道:
while(q.dQ()!){
System.out.println(q.dQ());}但这是错误的
发布于 2018-11-30 20:08:18
您可以在Queue类中定义另一个方法来检查队列是否为空。类似于:
static boolean isEmpty(){
// returns true is both stacks are empty
if(s1.isEmpty() && s2.isEmpty()){
return true;
}
return false;
}然后,您可以使用循环打印队列,如下所示:
while(! q.isEmpty()){
System.out.println(q.dQ());
}https://stackoverflow.com/questions/53555631
复制相似问题