1.用栈实现队列
/*
用两个栈来实现队列
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:37.5 MB, 在所有 Java 提交中击败了7.14%的用户
*/private Stack<Integer> s1 ;private Stack<Integer> s2 ;/** Initialize your data structure here. */publicMyQueue(){
s1 =newStack<>();
s2 =newStack<>();}/** Push element x to the back of queue. */publicvoidpush(int x){
s1.add(x);}/** Removes the element from in front of queue and returns that element. */publicintpop(){if(s1.isEmpty()&&s2.isEmpty()){return-1;}if(!s1.isEmpty()&&s2.isEmpty()){while(!s1.isEmpty()){
s2.add(s1.pop());}}return s2.pop();}/** Get the front element. */publicintpeek(){if(s1.isEmpty()&&s2.isEmpty()){return-1;}if(!s1.isEmpty()&&s2.isEmpty()){while(!s1.isEmpty()){
s2.add(s1.pop());}}return s2.peek();}/** Returns whether the queue is empty. */publicbooleanempty(){if(s1.isEmpty()&&s2.isEmpty()){returntrue;}else{returnfalse;}}
2.用队列实现栈
/*
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:37.5 MB, 在所有 Java 提交中击败了7.41%的用户
*/classMyStack{private Queue<Integer> q1;private Queue<Integer> q2;/**
* Initialize your data structure here.
*/publicMyStack(){
q1 =newLinkedList<>();
q2 =newLinkedList<>();}/**
* Push element x onto stack.
*/publicvoidpush(int x){
q1.add(x);}/**
* Removes the element on top of the stack and returns that element.
*/publicintpop(){if(q1.isEmpty()&& q2.isEmpty()){return-1;}int temp =0;if(!q1.isEmpty()){while(!q1.isEmpty()){
temp = q1.remove();
q2.add(temp);}
q2.remove(temp);}else{while(!q2.isEmpty()){
temp = q2.remove();
q1.add(temp);}
q1.remove(temp);}return temp;}/**
* Get the top element.
*/publicinttop(){if(q1.isEmpty()&& q2.isEmpty()){return-1;}int temp =0;if(!q1.isEmpty()){while(!q1.isEmpty()){
temp = q1.remove();
q2.add(temp);}}else{while(!q2.isEmpty()){
temp = q2.remove();
q1.add(temp);}}return temp;}/**
* Returns whether the stack is empty.
*/publicbooleanempty(){if(q1.isEmpty()&& q2.isEmpty()){returntrue;}else{returnfalse;}}}