Implement Queue using Stacks

[抄题]:

[思维问题]:

[一句话思路]:

取头部、取出来的时候,用一个output来倒序

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. this.queue = new LinkedList<Integer>(); queue的本质是链表,右边要写成linkedlist

[总结]:

[复杂度]:Time complexity: O() Space complexity: O()

[英文数据结构,为什么不用别的数据结构]:

[其他解法]:

[Follow Up]:

[题目变变变]:

class MyQueue {
Stack<Integer> input = new Stack();
Stack<Integer> output = new Stack(); public MyQueue() {
this.input = new Stack<Integer>();
this.output = new Stack<Integer>();
} /** Push element x to the back of queue. */
public void push(int x) {
input.push(x);
} /** Removes the element from in front of queue and returns that element. */
public int pop() {
peek();
return output.pop();
} /** Get the front element. */
public int peek() {
if (output.empty()) {
while (!input.empty()) {
output.push(input.pop());
}
}
return output.peek();
} /** Returns whether the queue is empty. */
public boolean empty() {
if(output.empty() && input.empty()) {
return true;
}
return false;
}
}

Implement Stack using Queues

[抄题]:

[思维问题]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. this.queue = new LinkedList<Integer>(); 右边是LinkedList
  2. Queue的push要先把新元素加进去。不然怎么去挤谁呢……
  3. queue的操作语言是poll, add。stack是push/pop
  4. 判断空都写isempty

[二刷]:

  1. 取top时要用peek方法,直接用poll取出来的不一定是最大的
  2. 一开始只需要初始化数据结构,不需要新建对象:Queue<Integer> queue;

[总结]:

[复杂度]:Time complexity: O() Space complexity: O()

[英文数据结构,为什么不用别的数据结构]:

[其他解法]:

[Follow Up]:

[题目变变变]:

class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
this.queue = new LinkedList<Integer>();
} /** Push element x onto stack. */
public void push(int x) {
queue.add(x);
for (int i = 0; i < queue.size() - 1; i++) {
queue.add(queue.poll());
}
} /** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
} /** Get the top element. */
public int top() {
return queue.peek();
} /** Returns whether the stack is empty. */
public boolean empty() {
if (queue.isEmpty()) {
return true;
}
return false;
}
}

最新文章

  1. .NET开源项目介绍及资源推荐:数据持久层
  2. cocos 的CCScheduler模块
  3. 关于我和document.write那点不得不说的事
  4. Python核心编程读笔 5: python的序列
  5. 配置nexus仓库
  6. 【分块】BZOJ2821 作诗(Poetize)
  7. Leetcode_278_First Bad Version
  8. css 生成图片添加的十字
  9. python 高阶函数之 reduce
  10. mongodb副本集基于centos7部署
  11. 解题报告 『[NOI2003]逃学的小孩(树上操作)』
  12. net spider(python 网络爬虫)
  13. Effective前端2---加快页面打开速度
  14. IDEA 的Class not found: &quot;...&quot;Empty test suite
  15. java 实现唯一ID生成器
  16. iOS多版本多设备适配的问题
  17. JavaEE Servlet 学习笔记
  18. no-siteapp 和 no-transform
  19. python开发_tkinter_图片操作
  20. 浅谈PCIe体系结构(详细剖析PCIE数据流向)

热门文章

  1. javascript面向对象之Object.defineProperty(a,b,c)
  2. Docker集群管理(二)—— docker+swarm+etcd+shipyard
  3. ElasticSearch 在3节点集群的启动
  4. 15.python操作mysql
  5. tomcat启动项目 端口占用
  6. NavitForMySql 破解工具使用
  7. vue常用
  8. DateFormat工具类
  9. TEXT 8 Ready, fire, aim
  10. Haskell语言学习笔记(52)正则表达式