顺序栈入栈出栈操作,输出一个数n,再输入n个字符,将每个字符依次入栈,再依次将字符出栈。
时间: 2023-04-30 18:00:53 浏览: 357
入栈和出栈的基本操作
5星 · 资源好评率100%
好的,以下是顺序栈入栈出栈操作的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
void push(Stack *s, char c) {
if (isFull(s)) {
printf("Stack is full.\n");
exit(1);
}
s->top++;
s->data[s->top] = c;
}
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
exit(1);
}
char c = s->data[s->top];
s->top--;
return c;
}
int main() {
int n;
printf("请输入一个数n:");
scanf("%d", &n);
Stack s;
initStack(&s);
printf("请输入%d个字符:", n);
for (int i = ; i < n; i++) {
char c;
scanf(" %c", &c);
push(&s, c);
}
printf("出栈顺序为:");
while (!isEmpty(&s)) {
char c = pop(&s);
printf("%c ", c);
}
printf("\n");
return ;
}
```
运行结果示例:
```
请输入一个数n:5
请输入5个字符:a b c d e
出栈顺序为:e d c b a
```
希望能够帮到你!
阅读全文