c语言创建一个顺序栈的代码
时间: 2023-12-25 21:02:05 浏览: 79
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} SeqStack;
SeqStack* initStack() {
SeqStack *stack = (SeqStack*)malloc(sizeof(SeqStack));
stack->top = -1;
return stack;
}
int isFull(SeqStack *stack) {
return stack->top == MAX_SIZE - 1;
}
int isEmpty(SeqStack *stack) {
return stack->top == -1;
}
void push(SeqStack *stack, int value) {
if (isFull(stack)) {
printf("Stack is full, can't push anymore\n");
return;
}
stack->data[++stack->top] = value;
}
int pop(SeqStack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty, can't pop anymore\n");
return -1;
}
return stack->data[stack->top--];
}
int top(SeqStack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty, no top value\n");
return -1;
}
return stack->data[stack->top];
}
int main() {
SeqStack *stack = initStack();
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("Top element of stack: %d\n", top(stack));
printf("Popped element from stack: %d\n", pop(stack));
printf("Top element of stack: %d\n", top(stack));
free(stack);
return 0;
}
```
这段代码是用C语言实现了一个顺序栈,并包括了初始化栈、判空、判满、入栈、出栈、获取栈顶元素等操作。在主函数中进行了栈的初始化,并进行了入栈、出栈和获取栈顶元素的操作。
阅读全文