入队思路:首先确定一个栈用于存放数据,直接将新的数据放到这个栈。
出队思路:队列要求先入先出,所以将存有数据的栈除最先进入的数据外依次存到另一个栈里面去并出栈,剩余的哪个即是需要真正出栈的数据
//栈类
class SqStack {
private int top;
private int[] elem;
private int usesize = 0;
public SqStack() {
this(10);
}
public SqStack(int size) {
this.top = -1;
this.elem = new int[size];
}
//是否为空
public boolean isEmpty() {
return usesize == 0;
}
//是否为满
public boolean isFull() {
return usesize == 10;
}
//入栈pups
public void push(int val) {
if (isFull()) {
throw new UnsupportedOperationException("栈满了");
}
elem[++top] = val;
usesize++;
}
//出栈
public void pop() {
if (isEmpty()) {
throw new UnsupportedOperationException("栈空了");
}
elem[top--] = 0;
usesize--;
}
public int getUsesize() {
return usesize;
}
//得到栈顶元素
public int getTop() {
return elem[top];
}
//打印函数
public void show() {
for (int i = 0; i <= top; i++) {
System.out.print(elem[i] + " ");
}
System.out.println();
}
}
//使用两个栈实现队列
class Queue {
SqStack stack1;
SqStack stack2;
public Queue() {
stack1 = new SqStack();
stack2 = new SqStack();
}
//入队
public void push(int val) {
// 把元素放到一个栈里面。
stack1.push(val);
}
// 出队
public void pop() {
//出队需要借助于第二个栈,需要把除要出队的节点之外的所有节点全部放到另外一个栈里面
while (stack1.getUsesize()>1) {
stack2.push(stack1.getTop());
stack1.pop();
}
stack1.pop(); //弹出此元素
while (stack2.getUsesize()>0) {
stack1.push(stack2.getTop());
stack2.pop();
}
}
//打印函数
public void show() {
stack1.show();
}
}
使用两个栈实现队列
最新推荐文章于 2024-04-22 23:20:09 发布