应该做哪些更正?

问题描述 投票:0回答:1

我正在尝试使用 C 在数据结构中创建堆栈。三个文件是 .h main.c 和methods.c。预期声明说明符或“Stack”之前的“...”存在问题 int peek(Stack * stack)在.h文件和methods.c文件中。

我找不到错误的原因。你能修好它吗? .h

#ifndef stackArray
#define stackArray

#define MAX_SIZE 10

struct StackNode{

    int data[MAX_SIZE];
    struct StackNode *top;

} Stack;

void initialize(Stack *stack);
int isFull(Stack *stack);
int isEmpty(Stack *stack);
void push(Stack *stack, int value);
int pop(Stack *stack);
int peek(Stack *stack);


#endif

main.c

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

int main() {
    Stack stack;
    initialize(&stack);

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

    if (!isEmpty(&stack)) {
        printf("Top element: %d\n", peek(&stack));
    } else {
        printf("Stack is empty\n");
    }

    printf("Popped: %d\n", pop(&stack));
    printf("Popped: %d\n", pop(&stack));

    if (!isEmpty(&stack)) {
        printf("Top element: %d\n", peek(&stack));
    } else {
        printf("Stack is empty\n");
    }

    return 0;
}

方法.c

#include "stackArray.h"
#include <stdio.h>

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

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

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

void push(Stack *stack, int value) {
    if (isFull(stack)) {
        printf("Stack Overflow: Cannot push element %d\n", value);
        return;
    }

    stack->data[++stack->top] = value;
    printf("Pushed %d onto the stack\n", value);
}

int pop(Stack *stack) {
    if (isEmpty(stack)) {
        printf("Stack Underflow: Cannot pop from an empty stack\n");
        return -1; // Return a sentinel value to indicate underflow
    }

    return stack->data[stack->top--];
}

int peek(Stack *stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty\n");
        return -1; // Return a sentinel value to indicate underflow
    }

    return stack->data[stack->top];
}

arrays c data-structures linked-list stack
1个回答
0
投票

这个:

struct StackNode{

    int data[MAX_SIZE];
    struct StackNode *top;

} Stack;

定义一个名为

struct StackNode
的结构体,并创建该结构体的一个名为 Stack
实例
。它创建类型。

为此,您需要使用

typedef

typedef struct StackNode{

    int data[MAX_SIZE];
    struct StackNode *top;

} Stack;
© www.soinside.com 2019 - 2024. All rights reserved.