牛客网刷题之用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型

java实现:
原理:
栈的特点:先进后出;
队列的特点:先进先出;
先将数据放入一个栈,然后取出放入另一个栈中,从这个栈中取出的数据就是类似队列的先进先出了;另外由于push和pop操作时间隔的,所以每次插入数据的时候需要先将数据从第二个栈中取出,放入第一个栈中,然后再插入数据。

package offer.test;

import java.util.Stack;

/**
 * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
 *
 */
public class StackQueue {

	Stack<Integer> stack1 = new Stack<Integer>();
	Stack<Integer> stack2 = new Stack<Integer>();

	public void push(int node) {
		while(!stack2.isEmpty()){
			stack1.push(stack2.pop());
		}
		stack1.push(node);
	}

	public int pop() {
		while(!stack1.isEmpty()){
			stack2.push(stack1.pop());
		}
		
		return stack2.pop();

	}
	
	public static void main(String[] args) {
		StackQueue stackQueue = new StackQueue();
		stackQueue.push(1);
		stackQueue.push(2);
		System.out.println(stackQueue.pop());
		stackQueue.push(3);
		System.out.println(stackQueue.pop());
		
		stackQueue.push(4);
		System.out.println(stackQueue.pop());
		stackQueue.push(5);
		System.out.println(stackQueue.pop());
		System.out.println(stackQueue.pop());
	}

}

你可能感兴趣的:(JAVA,牛客网)