C语言建立顺序栈,根据输入的栈中元素个数n和各元素值建立一个顺序栈,并打印出栈中各元素值。
时间: 2024-02-03 08:13:34 浏览: 112
以下是基于C语言实现的顺序栈,可以根据输入的元素个数和值构建一个顺序栈,并打印出栈中的元素值:
```
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 定义栈的最大容量
typedef struct {
int data[MAXSIZE];
int top;
} SqStack;
// 初始化栈
void InitStack(SqStack *s) {
s->top = -1; // 栈顶指针初始化为-1
}
// 判断栈是否为空
int StackEmpty(SqStack *s) {
return (s->top == -1);
}
// 入栈操作
int Push(SqStack *s, int x) {
if (s->top == MAXSIZE - 1) { // 栈满
return 0;
}
s->top++; // 栈顶指针加1
s->data[s->top] = x; // 将元素x压入栈顶
return 1;
}
// 出栈操作
int Pop(SqStack *s, int *x) {
if (s->top == -1) { // 栈空
return 0;
}
*x = s->data[s->top]; // 将栈顶元素弹出,存放在x指针所指的单元中
s->top--; // 栈顶指针减1
return 1;
}
int main() {
SqStack s;
int n, i, x;
printf("请输入栈中元素个数:");
scanf("%d", &n);
InitStack(&s); // 初始化栈
printf("请输入%d个元素值:", n);
for (i = 0; i < n; i++) {
scanf("%d", &x);
Push(&s, x); // 将元素x入栈
}
printf("顺序栈中的元素值为:");
while (!StackEmpty(&s)) {
Pop(&s, &x); // 将栈顶元素弹出,存放在x中
printf("%d ", x);
}
printf("\n");
return 0;
}
```
输入栈中元素个数n和各元素值后,程序会依次将这些元素入栈,并打印出栈中的所有元素值。
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)