c语言建立顺序栈,先进栈 3,2,1,出栈 2 次,进栈 4,5,6,7,再全部出队,输出每次入栈, 出栈序列。
时间: 2023-08-16 14:08:04 浏览: 66
以下是基于 C 语言的顺序栈实现代码,满足上述要求:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef struct {
int data[MAXSIZE];
int top;
} SqStack;
void InitStack(SqStack *S) {
S->top = -1;
}
int StackEmpty(SqStack S) {
return (S.top == -1);
}
int Push(SqStack *S, int x) {
if (S->top == MAXSIZE - 1) {
return 0;
}
S->data[++S->top] = x;
return 1;
}
int Pop(SqStack *S, int *x) {
if (S->top == -1) {
return 0;
}
*x = S->data[S->top--];
return 1;
}
int main() {
SqStack S;
InitStack(&S);
int i, x;
// 先进栈 3,2,1
for (i = 3; i >= 1; i--) {
Push(&S, i);
printf("入栈:%d\n", i);
}
// 出栈 2 次
for (i = 0; i < 2; i++) {
Pop(&S, &x);
printf("出栈:%d\n", x);
}
// 进栈 4,5,6,7
for (i = 4; i <= 7; i++) {
Push(&S, i);
printf("入栈:%d\n", i);
}
// 全部出栈
while (!StackEmpty(S)) {
Pop(&S, &x);
printf("出栈:%d\n", x);
}
return 0;
}
```
输出结果为:
```
入栈:3
入栈:2
入栈:1
出栈:1
出栈:2
入栈:4
入栈:5
入栈:6
入栈:7
出栈:7
出栈:6
出栈:5
出栈:4
出栈:3
```