import java.util.Stack;
class newQueue{
	Stack<Integer> s1 = new Stack<Integer>();
	Stack<Integer> s2 = new Stack<Integer>();
	
	public void add(int value) {
		s1.push(value);
	}
	
	public int pop() {
		if (s1.isEmpty() && s2.isEmpty()) {
			return -1;
		} else {
			while (!s1.isEmpty()) {
				s2.push(s1.pop());
			}
			return s2.pop();
		}
	}
	
	public int peek() {
		if (s1.isEmpty() && s2.isEmpty()) {
			return -1;
		} else {
			while (!s1.isEmpty()) {
				s2.push(s1.pop());
			}
			return s2.peek();
		}
	}
}

没错我就是灵魂画手!
用两个栈来实现队列

public static void main(String[] args) {
		newQueue N = new newQueue();
		N.add(1);
		N.add(2);
		N.add(3);
		N.add(4);
		N.add(5);
		int peek1 = N.peek();
		System.out.println(peek1);
		N.pop();
		N.pop();
		int peek2 = N.peek();
		System.out.println(peek2);
	}

用两个栈来实现队列

相关文章:

  • 2021-05-31
  • 2021-07-06
  • 2021-05-26
  • 2021-12-29
  • 2022-12-23
  • 2021-08-22
  • 2021-08-23
猜你喜欢
  • 2021-11-08
  • 2021-07-31
  • 2022-12-23
  • 2021-05-23
  • 2022-12-23
相关资源
相似解决方案