怎样做月嫂网站,中国工程网亿美,傻瓜式网站开发工具,wordpress 倒计时栈和队列#xff08;Java#xff09; Java中的 栈 队列 操作栈的使用队列的使用 LeetCode 232. 用栈实现队列我的代码 LeetCode 225. 用队列实现栈我的代码 Java中的 栈 队列 操作
栈的使用
栈的方法功能Stack()构造一个空的栈E push(E e)将e入栈#xff0c;并… 栈和队列Java Java中的 栈 队列 操作栈的使用队列的使用 LeetCode 232. 用栈实现队列我的代码 LeetCode 225. 用队列实现栈我的代码 Java中的 栈 队列 操作
栈的使用
栈的方法功能Stack()构造一个空的栈E push(E e)将e入栈并返回eE pop()将栈顶元素出栈并返回E peek()获取栈顶元素int size()获取栈中有效元素个数Boolean empty()检测栈是否为空
StackString s new Stack();
StackIntger s2 new Stack();队列的使用
队列的方法功能Boolean offer(E e)入队列E poll()队头元素出队列并返回E peek()获取队头元素int size()获取队列中有效元素个数Boolean isEmpty()检测队列是否为空
注意 Queue 是个接口在实例化时必须实例化 LinkedList 的对象因为 LinkedList 实现了 Queue 接口。
QueueInteger q new LinkedList();LeetCode 232. 用栈实现队列
出错点分析 ①栈的新建不会写、栈的操作方法不清楚 ②可以看到 pop 和 peek 函数实现的逻辑都是一样的很冗余没有示例代码写的简洁
我的代码
class MyQueue {StackInteger s1 new Stack();StackInteger s2 new Stack();public MyQueue() {}public void push(int x) {s1.push(x);}public int pop() {while(s1.size() ! 0) {int tmp s1.pop();s2.push(tmp);}int ans s2.pop();while(s2.size() ! 0) {int tmp s2.pop();s1.push(tmp);}return ans;}public int peek() {while(s1.size() ! 0) {int tmp s1.pop();s2.push(tmp);}int ans s2.peek();while(s2.size() ! 0) {int tmp s2.pop();s1.push(tmp);}return ans;}public boolean empty() {return s1.empty();}
}LeetCode 225. 用队列实现栈
出错点分析 ①队列的新建不会写、队列的操作方法不清楚 ②可以看到 pop 和 top 函数实现的逻辑都是一样的很冗余没有示例代码写的简洁
我的代码
class MyStack {QueueInteger q1new LinkedList();QueueInteger q2new LinkedList();public MyStack() {}public void push(int x) {q1.offer(x);}public int pop() {//移除并返回栈顶元素。while(q1.size() ! 1) {int tmp q1.poll();q2.offer(tmp);}int ans q1.poll();while(q2.size() ! 0) {int tmp q2.poll();q1.offer(tmp);}return ans;}public int top() {int ans -1;//要赋初值while(q1.size() ! 0) {int tmp q1.poll();q2.offer(tmp);if(q1.size() 0) { //是等于0的时候而不是等于1因为poll操作暗含了size-1ans tmp;}}while(q2.size() ! 0) {int tmp q2.poll();q1.offer(tmp);}return ans;}public boolean empty() {return q1.isEmpty();}
}