两个栈实现一个队列
来源:互联网 发布:linux统计ls-l行数 编辑:程序博客网 时间:2024/05/22 10:39
九度OJ1512 http://ac.jobdu.com/problem.php?pid=1512
剑指offer面试题7
思路分析
两个队列,一个“入栈”inStack,当有数据进入队列时,只往inStack里压栈;一个“出栈”outStack,当有数据出队列时,只能从outStack中出。
代码实现
使用c++实现
#include<cstdio>#include<stack>#include<cstring>using namespace std;class MyQueue {public: void PUSH(int); void POP();private: stack<int> inStack; stack<int> outStack;};void MyQueue::PUSH(int val) { inStack.push(val);}void MyQueue::POP(void) { if (outStack.empty()) { if (inStack.empty()) { printf("-1\n"); return; } else { while (!inStack.empty()) { outStack.push(inStack.top()); inStack.pop(); } } } printf("%d\n", outStack.top()); outStack.pop();}int main() { int n; MyQueue que; scanf("%d", &n); for (int i = 0; i != n; ++i) { char MyOrder[5]; //只需5个空间即可("PUSH"4个字符加上末尾的'\0') scanf("%s", MyOrder); if (strcmp("PUSH", MyOrder) == 0) { int val; scanf("%d", &val); que.PUSH(val); } else if (strcmp("POP", MyOrder) == 0) { que.POP(); } else { return 0; } } return 0;}/************************************************************** Problem: 1512 User: buptxxz Language: C++ Result: Accepted Time:70 ms Memory:1184 kb****************************************************************/
使用java实现
import java.util.Scanner;import java.util.Stack;public class Main { Stack<Integer> inStack = new Stack<Integer>(); Stack<Integer> outStack = new Stack<Integer>(); public void push(int e) { inStack.push(e); } public void pop() { if (inStack.empty() && outStack.empty()) { System.out.println(-1); } else if (outStack.empty()) { while (!inStack.empty()) { outStack.push(inStack.pop()); } System.out.println(outStack.pop()); } else { System.out.println(outStack.pop()); } } public static void main(String[] args) { Main M = new Main(); Scanner cin = new Scanner(System.in); String kaseNum = cin.nextLine(); int kase = Integer.parseInt(kaseNum); for (int i = 0; i < kase; ++i) { String cmd = cin.next(); if ("PUSH".equals(cmd)) { int elem = Integer.parseInt(cin.next()); M.push(elem); } else { M.pop(); } } cin.close(); } // main} // class/************************************************************** Problem: 1512 User: buptxxz Language: Java Result: Accepted Time:2150 ms Memory:104104 kb****************************************************************/
0 0
- 两个队列实现一个栈&两个栈实现一个队列
- 两个栈实现一个队列-----两个队列实现一个栈
- 两个栈实现一个队列&&两个队列实现一个栈
- 两个栈实现一个队列 && 两个队列实现一个栈
- 两个栈实现一个队列,两个队列实现一个栈
- 两个栈实现一个队列/两个队列实现一个栈
- 两个栈实现一个队列&两个队列实现一个栈
- 两个队列实现一个栈&两个栈实现一个队列
- 两个队列实现一个栈 / 两个栈实现一个队列
- 两个栈实现一个队列,两个队列实现一个栈
- 两个栈实现一个队列&两个队列实现一个栈
- 两个栈实现一个队列&&两个队列实现一个栈
- 两个栈实现一个队列&两个队列实现一个栈
- 两个栈实现一个队列/两个队列实现一个栈
- 两个栈实现一个队列
- 两个栈实现一个队列
- 两个栈实现一个队列
- 两个栈实现一个队列
- 持有对象
- 关于最小堆以及priority_queue
- yarn原理介绍
- 从数据库调出数据显示到页面 PHP+Mysql+Html(简单实例)
- Mysql常见的索引类型
- 两个栈实现一个队列
- java环境变量配置
- uva11478(spfa求负环)
- python爬虫学习--pixiv爬虫(3)--关注用户作品爬取
- Libgdx之Sprite 精灵类
- 如何在GitHub上建立项目演示页面
- leetcode之Odd Even Linked List
- 连封面都是递归——《你好哇,程序员——漫话程序员面试求职、升职加薪、创业与生活》
- Tsinsen A1110 街道