classMyStack{Queue<Integer> queue1;// 和栈中保持一样元素的队列Queue<Integer> queue2;// 辅助队列/**
* Initialize your data structure here.
*/publicMyStack(){
queue1 =newLinkedList<>();
queue2 =newLinkedList<>();}/**
* Push element x onto stack.
*/publicvoidpush(int x){
queue2.offer(x);// 先放在辅助队列中while(!queue1.isEmpty()){
queue2.offer(queue1.poll());}Queue<Integer> queueTemp;
queueTemp = queue1;
queue1 = queue2;
queue2 = queueTemp;// 最后交换queue1和queue2,将元素都放到queue1中}/**
* Removes the element on top of the stack and returns that element.
*/publicintpop(){return queue1.poll();// 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可}/**
* Get the top element.
*/publicinttop(){return queue1.peek();}/**
* Returns whether the stack is empty.
*/publicbooleanempty(){return queue1.isEmpty();}}
用一个队列实现
思路
每次弹栈把队列中的所有元素都移到队列末尾除了最后一个元素
classMyStack{Queue<Integer> queue1;/**
* Initialize your data structure here.
*/publicMyStack(){
queue1 =newLinkedList<>();}/**
* Push element x onto stack.
*/publicvoidpush(int x){
queue1.offer(x);}/**
* Removes the element on top of the stack and returns that element.
*/publicintpop(){int size = queue1.size()-1;//因为要保留最后一个所以先提前减一while(size-->0){
queue1.offer(queue1.poll());}return queue1.poll();}/**
* Get the top element.
*/publicinttop(){int result =this.pop();
queue1.offer(result);return result;}/**
* Returns whether the stack is empty.
*/publicbooleanempty(){return queue1.isEmpty();}}
classSolution{publicStringremoveDuplicates(String s){Stack<Character> stack =newStack<>();for(int i =0; i < s.length(); i++){if(stack.isEmpty()|| s.charAt(i)!= stack.peek()){
stack.push(s.charAt(i));}else{
stack.pop();}}StringBuilder stringBuilder =newStringBuilder();
stack.stream().forEach(character -> stringBuilder.append(character));return stringBuilder.toString();}}
字符串实现
字符串替换栈
classSolution{publicStringremoveDuplicates(String s){StringBuilder res =newStringBuilder();for(int i =0; i < s.length(); i++){if(res.length()==0|| s.charAt(i)!= res.charAt(res.length()-1)){
res.append(s.charAt(i));}else{
res.deleteCharAt(res.length()-1);}}return res.toString();}}