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

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

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

  • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
 
 两个栈实现队列。
1 class Queue { 2 private: 3     stack
stack1,stack2; 4 public: 5 // Push element x to the back of queue. 6 void push(int x) { 7 8 stack1.push(x); 9 10 }11 12 // Removes the element from in front of queue.13 void pop(void) {14 if(stack2.empty())15 {16 while(!stack1.empty())17 {18 stack2.push(stack1.top());19 stack1.pop();20 }21 }22 stack2.pop();23 24 }25 26 // Get the front element.27 int peek(void) {28 if(stack2.empty())29 {30 while(!stack1.empty())31 {32 stack2.push(stack1.top());33 stack1.pop();34 }35 }36 return stack2.top();37 38 39 }40 41 // Return whether the queue is empty.42 bool empty(void) {43 if(stack1.empty()&&stack2.empty())44 return true;45 else46 return false;47 48 }49 };

 

转载于:https://www.cnblogs.com/xiaoying1245970347/p/4723529.html

你可能感兴趣的文章
判断页面加载
查看>>
8年前,《西班牙,我为你哭泣。》
查看>>
SVN:服务器资源删掉,本地添加时和删掉的名字同名出现One or more files are in a conflicted state....
查看>>
MySQL数据库遭到攻击篡改---使用备份和binlog进行数据恢复
查看>>
如何在Java中定义常量(Constant)
查看>>
Windows 8实用窍门系列:8.Windows 8 中Slider控件和ToggleSwitch控件
查看>>
在IIS 7.0中架设网站,并用VS2005来调试Web项目
查看>>
白话学习MVC(七)Action的执行一
查看>>
javaweb学习总结(四)——Http协议
查看>>
GridView实战二:使用ObjectDataSource数据源控件
查看>>
C# 视频监控系列(3):客户端——连接服务器并预览
查看>>
oracle表空间使用率统计查询
查看>>
virtualbox不能安装64位操作系统
查看>>
MyBatis Generator(MBG)Oracle使用说明 公共同义词 LONG数据类型
查看>>
ORA-00918:未明确定义列
查看>>
控件如何禁止手动输入(转载)
查看>>
为什么Java byte 类型的取值范围是-128~127
查看>>
ElasticSearch怎样加入,检索数据
查看>>
redis事务
查看>>
Cloud Foundry体验
查看>>