温馨提示×

C语言栈怎样实现

小樊
87
2024-07-24 20:18:19
栏目: 编程语言

在C语言中,栈可以使用数组或链表来实现。以下是一种使用数组实现栈的方法:

#include <stdio.h>

#define MAX_SIZE 100

typedef struct {
    int arr[MAX_SIZE];
    int top;
} Stack;

void init(Stack *stack) {
    stack->top = -1;
}

int isEmpty(Stack *stack) {
    return stack->top == -1;
}

int isFull(Stack *stack) {
    return stack->top == MAX_SIZE - 1;
}

void push(Stack *stack, int value) {
    if (isFull(stack)) {
        printf("Stack is full\n");
        return;
    }
    stack->top++;
    stack->arr[stack->top] = value;
}

int pop(Stack *stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty\n");
        return -1;
    }
    int value = stack->arr[stack->top];
    stack->top--;
    return value;
}

int peek(Stack *stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty\n");
        return -1;
    }
    return stack->arr[stack->top];
}

int main() {
    Stack stack;
    init(&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: %d\n", isEmpty(&stack));

    return 0;
}

这段代码定义了一个栈结构体,包括一个整型数组和栈顶指针。使用init函数初始化栈,isEmptyisFull函数判断栈是否为空或满。push函数用于入栈,pop函数用于出栈,peek函数用于获取栈顶元素但不出栈。在main函数中演示了栈的基本操作。

0