博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Implement Stack using Queues
阅读量:6983 次
发布时间:2019-06-27

本文共 1952 字,大约阅读时间需要 6 分钟。

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:

  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Update (2015-06-11):

The class name of the Java function had been updated to MyStack instead of Stack.

思路分析:这题和相似,思路也相似。用两个队列来模拟一个栈。详细做法是。入栈仅仅须要放入Q1队列尾部。出栈时。把Q1除了最后一个元素之外的全部元素出队列。而且压入Q2队列尾部。然后从Q1中取出最后那个元素。注意要保证Q2为空,它是一个辅助队列。所以我们交换Q1和Q2。

top和pop方法相似,除了取出Q1中最后那个元素后,再返回它前还要压入到Q2中去。保证这个元素不被丢失,由于我们仅仅想看栈顶元素,并不想真正将它出栈。

AC Code

class MyStack {       //Queue   LinkedList
q1 = new LinkedList
(); LinkedList
q2 = new LinkedList
(); // Push element x onto stack. public void push(int x) { q1.add(x); } // Removes the element on top of the stack. public void pop() { //peek(); poll(); while(q1.size() > 1){ q2.add(q1.poll()); } q1.poll(); //switch LinkedList
tem = q1; q1 = q2; q2 = tem; } // Get the top element. public int top() { //peek(); poll(); while(q1.size() > 1){ q2.add(q1.poll()); } int res = q1.peek(); q2.add(q1.poll()); //switch LinkedList
tem = q1; q1 = q2; q2 = tem; return res; } // Return whether the stack is empty. public boolean empty() { return q1.isEmpty(); }}

转载于:https://www.cnblogs.com/yutingliuyl/p/6746275.html

你可能感兴趣的文章
综合布线系统的构成
查看>>
计算机硬件 — 计算机简介
查看>>
关于重写session实现的时候可能会导至nginx 502的问题
查看>>
7z(p7zip)压缩软件在Linux下的安装和使用
查看>>
jetbrick-template 1.1.0 发布,支持 #tag, #macro, layout
查看>>
TCP的六个控制位
查看>>
numpy库中的extend()函数使用
查看>>
进制转换
查看>>
我的友情链接
查看>>
新书上市:《FLUENT 14.0超级学习手册》
查看>>
mysql数据库query cache
查看>>
使用docker commit 来扩展一个image
查看>>
jsp 防止sql注入 之 preparestatement篇(转载)
查看>>
Linux之Ansible入门用法(实验解析)
查看>>
Linux系统如何在开机时修改root密码
查看>>
共济失调对我们的危害你知道吗
查看>>
Anychat的绝对路径与相对路径
查看>>
我的友情链接
查看>>
如何使用网络库实现应用级消息收发
查看>>
Single Area OSPF
查看>>