写一个可以运行的c语言栈程序
时间: 2023-11-26 19:04:07 浏览: 17
好的,这里提供一个可以运行的c语言栈程序,使用数组实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 // 定义栈的最大长度
typedef struct {
int data[MAX_SIZE];
int top; // 栈顶指针
} Stack;
Stack* createStack() // 初始化栈
{
Stack* s = (Stack*)malloc(sizeof(Stack));
s->top = -1; // 初始化栈顶指针为-1
return s;
}
void push(Stack* s, int x) // 入栈操作
{
if (s->top == MAX_SIZE - 1) {
printf("Stack overflow.\n");
return;
}
s->top++;
s->data[s->top] = x;
}
int pop(Stack* s) // 出栈操作
{
if (s->top == -1) {
printf("Stack underflow.\n");
return -1;
}
int x = s->data[s->top];
s->top--;
return x;
}
int top(Stack* s) // 取栈顶元素操作
{
if (s->top == -1) {
printf("Stack is empty.\n");
return -1;
}
return s->data[s->top];
}
int isEmpty(Stack* s) // 判断栈是否为空操作
{
return s->top == -1;
}
int main()
{
Stack* s = createStack();
push(s, 1);
push(s, 2);
push(s, 3);
printf("栈顶元素为:%d\n", top(s));
printf("出栈元素为:%d\n", pop(s));
printf("出栈元素为:%d\n", pop(s));
printf("出栈元素为:%d\n", pop(s));
printf("栈是否为空:%d\n", isEmpty(s));
return 0;
}
```
运行结果如下:
```
栈顶元素为:3
出栈元素为:3
出栈元素为:2
出栈元素为:1
栈是否为空:1
```
其中,栈顶元素为3,依次出栈元素为3、2、1,最后栈为空。