写一个关于栈的C语言代码
#include <stdio.h> #include <stdlib.h>
#define MAX_SIZE 100
typedef struct Stack { int top; int data[MAX_SIZE]; } Stack;
Stack* createStack() { Stack* stack = (Stack*) malloc(sizeof(Stack)); stack->top = -1; return stack; }
int isEmpty(Stack* stack) { return stack->top == -1; }
int isFull(Stack* stack) { return stack->top == MAX_SIZE - 1; }
void push(Stack* stack, int item) { if (isFull(stack)) { printf("Stack overflow\n"); return; } stack->data[++stack->top] = item; }
int pop(Stack* stack) { if (isEmpty(stack)) { printf("Stack underflow\n"); return -1; } return stack->data[stack->top--]; }
int peek(Stack* stack) { if (isEmpty(stack)) { printf("Stack underflow\n"); return -1; } return stack->data[stack->top]; }
int main() { Stack* stack = createStack();
push(stack, 1);
push(stack, 2);
push(stack, 3);
printf("Top element: %d\n", peek(stack));
printf("Pop element: %d\n", pop(stack));
printf("Top element: %d\n", peek(stack));
return 0;
}
原文地址: https://www.cveoy.top/t/topic/wQe 著作权归作者所有。请勿转载和采集!