编程介的小学生 2018-12-25 21:41 采纳率: 20.5%
浏览 428
已采纳

一个有关堆栈的合并方面的算法难题,比较难,用C语言

Problem Description
A stack is a data structure in which all insertions and deletions of entries are made at one end, called the "top" of the stack. The last entry which is inserted is the first one that will be removed. In another word, the operations perform in a Last-In-First-Out (LIFO) manner.
A mergeable stack is a stack with "merge" operation. There are three kinds of operation as follows:

  • push A x: insert x into stack A
  • pop A: remove the top element of stack A
  • merge A B: merge stack A and B

After an operation "merge A B", stack A will obtain all elements that A and B contained before, and B will become empty. The elements in the new stack are rearranged according to the time when they were pushed, just like repeating their "push" operations in one stack. See the sample input/output for further explanation.
Given two mergeable stacks A and B, implement operations mentioned above.

Input
There are multiple test cases. For each case, the first line contains an integer N(0<N≤105), indicating the number of operations. The next N lines, each contain an instruction "push", "pop" or "merge". The elements of stacks are 32-bit integers. Both A and B are empty initially, and it is guaranteed that "pop" operation would not be performed to an empty stack. N = 0 indicates the end of input.

Output
For each case, print a line "Case #t:", where t is the case number (starting from 1). For each "pop" operation, output the element that is popped, in a single line.

Sample Input
4
push A 1
push A 2
pop A
pop A
9
push A 0
push A 1
push B 3
pop A
push A 2
merge A B
pop A
pop A
pop A
9
push A 0
push A 1
push B 3
pop A
push A 2
merge B A
pop B
pop B
pop B
0

Sample Output
Case #1:
2
1
Case #2:
1
2
3
0
Case #3:
1
2
3
0

  • 写回答

1条回答 默认 最新

  • threenewbee 2019-08-28 22:28
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘