C语言栈怎样实现

   2024-10-05 6540
核心提示:在C语言中,栈可以使用数组或链表来实现。以下是一种使用数组实现栈的方法:#include stdio.h#define MAX_SIZE 100typedef struc

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

#include <stdio.h>#define MAX_SIZE 100typedef 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函数初始化栈,isEmpty和isFull函数判断栈是否为空或满。push函数用于入栈,pop函数用于出栈,peek函数用于获取栈顶元素但不出栈。在main函数中演示了栈的基本操作。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号