使用C语言实现栈的增删改查基本操作

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

// 栈结构
typedef struct {
    int data[MAX_SIZE];
    int top;
} Stack;

// 初始化栈
void initStack(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("栈已满,无法入栈\n");
        return;
    }

    stack->top++;
    stack->data[stack->top] = value;
    printf("入栈成功:%d\n", value);
}

// 出栈
int pop(Stack* stack) {
    if (isEmpty(stack)) {
        printf("栈为空,无法出栈\n");
        return -1;
    }

    int value = stack->data[stack->top];
    stack->top--;
    printf("出栈成功:%d\n", value);
    return value;
}

// 更新栈中指定位置的元素
void update(Stack* stack, int index, int value) {
    if (isEmpty(stack)) {
        printf("栈为空,无法更新元素\n");
        return;
    }

    if (index < 0 || index > stack->top) {
        printf("索引超出范围,无法更新元素\n");
        return;
    }

    stack->data[index] = value;
    printf("更新成功,位置 %d 的元素更新为:%d\n", index, value);
}

// 查找指定元素在栈中的位置
int search(Stack* stack, int value) {
    if (isEmpty(stack)) {
        printf("栈为空,无法查找元素\n");
        return -1;
    }

    for (int i = stack->top; i >= 0; i--) {
        if (stack->data[i] == value) {
            printf("元素 %d 在栈中的位置为:%d\n", value, i);
            return i;
        }
    }

    printf("栈中不存在元素 %d\n", value);
    return -1;
}

// 主函数
int main() {
    Stack stack;
    initStack(&stack);

    push(&stack, 10);
    push(&stack, 20);
    push(&stack, 30);

    int searchIndex = search(&stack, 20);

    if (searchIndex != -1) {
        update(&stack, searchIndex, 40);
    }

    pop(&stack);
    pop(&stack);

    return 0;
}

 

posted @ 2023-07-03 23:12  nullIsland01  阅读(95)  评论(0)    收藏  举报