用c语言写一个程序判断能否用栈将1~n的递增序列转换为指定序列 输入序列2,1,输出push(1),push(2),pop(2),pop(1)
时间: 2024-02-03 20:02:25 浏览: 13
```c
#include <stdio.h>
#define MAXN 1000
int stack[MAXN];
int top = -1;
void push(int x) {
stack[++top] = x;
printf("push(%d)\n", x);
}
int pop() {
printf("pop(%d)\n", stack[top]);
return stack[top--];
}
int main() {
int n, target[MAXN];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &target[i]);
}
int curr = 1; // 当前待压入栈中的数
for (int i = 0; i < n; i++) {
// 如果栈顶元素不是要弹出的数,则需要一直压入栈中
while (top == -1 || stack[top] != target[i]) {
if (curr > n) {
// 如果当前待压入栈中的数大于n,说明无法得到目标序列
printf("No\n");
return 0;
}
push(curr++);
}
pop();
}
printf("Yes\n");
return 0;
}
```