使用栈实现队列(2)(Java)

时间:2023-03-10 02:45:58
使用栈实现队列(2)(Java)
 class MyQueue
{
private Stack s1;
private Stack s2; public MyQueue(int size)
{
this.s1 = new Stack(size);
this.s2 = new Stack(size);
} public boolean isFull()
{
return s1.isFull();
} public boolean isEmpty()
{
return s1.isEmpty();
} //时间复杂度: O(n)
public void EnQueue(int k) throws Exception
{
if(s1.isFull())
throw new Exception("Overflow.");
else
{
while(!s1.isEmpty())
s2.push(s1.pop());
s1.push(k);
while(!s2.isEmpty())
s1.push(s2.pop());
}
} //时间复杂度: O(1)
public int DeQueue() throws Exception
{
if(s1.isEmpty())
throw new Exception("Underflow.");
else
return s1.pop();
}
} class Stack
{
private int top;
private int[] a; public Stack(int size)
{
this.top = -1;
this.a = new int[size];
} public boolean isFull()
{
return this.top == this.a.length - 1;
} public boolean isEmpty()
{
return this.top == -1;
} public void push(int k) throws Exception
{
/*if(this.isFull())
throw new Exception("Overflow.");*/
//else
this.a[++top] = k;
} public int pop() throws Exception
{
/*if(this.isEmpty())
throw new Exception("Underflow.");*/
//else
return this.a[top--];
} public int getLength()
{
return this.top + 1;
}
}