用两个栈实现队列
来源:互联网 发布:java培训那家口碑最高 编辑:程序博客网 时间:2024/05/16 01:07
- 题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。
- 输入:
每个输入文件包含一个测试样例。
对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。
接下来的n行,每行输入一个队列操作:
1. PUSH X 向队列中push一个整数x(x>=0)
2. POP 从队列中pop一个数。
- 输出:
对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。
- 样例输入:
3PUSH 10POPPOP
- 样例输出:
10-1
思路:
看图和代码的注释便能理解:
AC代码:
#include<stdio.h>#define N 100005 int stack1[N], stack2[N]; int main() { int n, top1, top2, v; char s[10]; while (scanf("%d", &n) != EOF) { top1 = 0, top2 = 0; while (n--) { scanf("%s", s); if (s[1] == 'U') { /*PUSH*/ scanf("%d", &v); stack1[top1++] = v; } else { if (top2 == 0) { /*只有把前面“倒过来”的数输出完,后面的数才能“倒过来”*/ while (top1) { /*类似于从一摞书A中自上向下取,放到第二摞书B中,实现了“倒栈”, 倒完了就是一个队列的顺序了*/ stack2[top2++] = stack1[--top1]; } } if (top2) { printf("%d\n", stack2[--top2]); } else { printf("-1\n"); } } } } return 0;} /************************************************************** Problem: 1512 User: wusuopuBUPT Language: C Result: Accepted Time:60 ms Memory:1696 kb****************************************************************/
0 0
- 用两个栈实现队列 & 用两个队列实现栈
- 用两个队列实现栈&用两个栈实现队列
- 用两个栈实现队列 & 两个队列实现一个栈
- 两个栈实现队列&&用两个队列实现一个栈
- 用两个栈实现队列 & 两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 给C语言添加花指令,抵御反汇编
- iOS7 Transition Guide
- 咨询转
- 优秀资源
- 获取某月份第N周开始日期(即星期一)
- 用两个栈实现队列
- 无损把硬盘从动态磁盘转化为基本磁盘和把主分区转化为逻辑分区
- python编程之简单入门
- LCD framebuffer驱动设计文档
- LINUX/UNIX下的回车换行与WINDOWS下的区别
- 去掉Word2007中的软回车(从网页粘贴文字的一些编辑)
- 【Java并发编程】并发新特性—阻塞队列和阻塞栈(含代码)
- 防OD附加的代码
- 系统分析之六 可行性分析和系统方案建议