两个栈表示队列的编程问题

使用两个栈来表示一个队列,需要考虑到的是栈的特点为先进后出,而队列的特点为先进先出,所以需要使用2个栈来表示这种关系。并且栈在JAVA中的可以建立一个对象,出栈调用stack.pop()方法,进栈调用stack.push(node)方法。知道这一点就很好去完成这个编程了。

对栈内压入元素前还需要考虑压入的栈是否为空,以及考虑被压入的栈是否为空

public class StackToQueue {
	
	Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
	
public void push(int node) {
	stack1.push(node);
}
public Integer pop() {
	if(stack2.empty()) {
		while(!stack1.empty()) {
			stack1.push(stack2.pop());
		}
	}
	return stack2.pop();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_29660957/article/details/89531536