当前位置: 首页 > 后端技术 > Java

LeetCode-225-Usingqueuestoimplementstack

时间:2023-04-01 23:24:11 Java

Usingqueuestoimplementstacks题目描述:请只用两个队列实现一个后进先出(LIFO)的栈,并支持普通队列的全部四种操作(push,top),pop和empty).实现MyStack类:voidpush(intx)将元素x压入栈顶。intpop()移除并返回栈顶元素。inttop()返回栈顶元素。booleanempty()如果栈为空则返回真;否则,返回false。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:双队列实现栈使用firstQueue和secondQueue两个队列来存储数据。具体方法如下:push(intx):如果firstQueue为空,则将x存入secondQueue,否则存入firstQueue;pop():如果firstQueue为空,取出secondQueue中的所有数据,一个一个的存入firstQueue,只留一个作为栈顶元素取出返回;否则,取出firstQueue中的所有数据,依次存入se??condQueue中,只留下一个作为栈顶元素,将栈顶元素取出并返回;top():逻辑类似于pop()方法;empty():如果firstQueue和secondQueue都为空,则返回true;否则,返回假。importjava.util.LinkedList;importjava.util.Queue;publicclassLeetCode_225{publicstaticvoidmain(String[]args){MyStackmyStack=newMyStack();myStack.push(1);myStack.push(2);myStack.push(3);System.out.println(myStack.top());//返回2System.out.println(myStack.pop());//返回2System.out.println(myStack.empty());//返回False}}classMyStack{privateQueuefirstQueue;私有队列<整数>secondQueue;/***在这里初始化你的数据结构。*/publicMyStack(){firstQueue=newLinkedList<>();secondQueue=newLinkedList<>();}/***将元素x压入堆栈。*/publicvoidpush(intx){if(firstQueue==null){secondQueue.add(x);}else{firstQueue.add(x);}}/***移除堆栈顶部的元素并返回该元素。*/publicintpop(){if(this.empty()){thrownewRuntimeException("emptystack.");}if(firstQueue.isEmpty()){intsize=secondQueue.size();for(inti=1;i