Subject description:
-
Two stacks to achieve a queue, the completion queue Push and Pop operations.
Queue elements int.
Input:
-
Each input file contains a test sample.
For each test sample, a first line of the input n (1 <= n <= 100000), the number representing the operation of the queue.
The next n lines, each line of the input queue operation:
1. Push the PUSH a X-integer x (x> = 0) to the queue
2. POP pop a number from the queue.
Output:
-
Corresponding to each test case, all the printing operations of the digital pop pop from the queue. If the pop operation performed, the queue is empty, the print -1
Sample input:
3
PUSH 10
POP
POP
Sample output:
10
-1
Problem-solving ideas:
- First subject of the request queue represents two stacks. It is best to use two stacks myself, although I do not know how OJ is detected, it should use a queue is not enough.
- Then we remembered the Tower of Hanoi, the stack itself is the last in the queue is FIFO. So how to design it?
- Two stacks, one stack for the first PUSH, a second stack for POP.
- Issues to note is that the order of elements around the middle of the two stacks can not be arbitrary. As long as there are elements in the stack 2 is present, it can not stack a stack 2 to the pressure element . such as
- New elements stack 1 3
- 2 is a stack of elements 21,
- Then the two stack list is:
3
2 1
- To order this time out of the stack must be
1 2 3
- At this time, if the stack 2 onto the stack 1, the order of the stack becomes
3 1 2
- Thus, it should not be guaranteed in the stack 2 when the element is empty, stack 2 again pushed onto the stack of element 1 .
Code:
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#define MAX 100001
int stack1[MAX],stack2[MAX],top1,top2;
int main(void){
int n,i,m;
char input1[10];
while(scanf("%d",&n)!=EOF && n<=100000 && n>= 1){
top1 = top2 = 0;
memset(&stack1,0,sizeof(int)*MAX);
memset(&stack2,0,sizeof(int)*MAX);
for(i=0;i<n;i++){
scanf("%s",input1);
if(strcmp(input1,"PUSH") == 0){
scanf("%d",&m);
stack1[top1++] = m;
}else{
if(top2 == 0){//判断栈2是否还存在元素
while(top1){
stack2[top2++] = stack1[--top1];
}
}
if(top2)//如果栈2中有元素,则弹出,否则,表示两个栈都没有元素
printf("%d\n",stack2[--top2]);
else{
printf("-1\n");
}
}
}
}
return 0;
}
Reproduced in: https: //my.oschina.net/u/204616/blog/545514