以下是一個基本的順序棧的C語言實現示例:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack is full\n");
return;
}
s->top++;
s->data[s->top] = value;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
int value = s->data[s->top];
s->top--;
return value;
}
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
return s->data[s->top];
}
int main() {
Stack stack;
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("Top element: %d\n", peek(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Is stack empty: %s\n", isEmpty(&stack) ? "true" : "false");
return 0;
}
這段代碼定義了一個基本的順序棧數據結構,包括初始化棧、判斷棧是否為空或滿、入棧、出棧、獲取棧頂元素的操作。在main函數中,進行了棧的初始化、入棧、出棧等操作,并打印了一些信息。
您可以根據自己的需求對該代碼進行修改和擴展。