堆栈实现的困难

Difficulties with implementation of stack

我正在尝试进入结构,但我被卡住了。这里我尝试实现栈的主要功能:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#define N 10

    struct docEdit 
{
    char text[20];
    int StrNum;
};


struct Stack {
    struct docEdit items[N];
    int top;
};
    
void pushstack(struct Stack* st, struct docEdit myEvent1) {
if (st->top == N - 1) {
    printf("Stack is full");
    return;
    }   
    
    st->items[st->top++] = myEvent1;
}

    void popstack(struct Stack* st) {
    if (st->top == -1) {
        printf("Stack is empty");
        return;
    }
        st->top--;
    }

    int emptystack(struct Stack* st) {
        return st->top = 0;
    }

    int sizestack(struct Stack* st) {
        return st->top;
    }

    (//function data type//) top(struct Stack* st) {
        return st->items[st->top];
    }



    int main() {
    setlocale(LC_ALL, "");
    struct Stack st;
    st.top = -1;
    struct docEdit myEvent1 = {"string 1", 1};

    pushstack(&st, myEvent1);
    popstack(&st);

    return 0;
    }

有两个问题:为什么写st变量没有初始化,top函数应该是什么数据类型?如果您能指出我的错误和不准确之处,我也将不胜感激。

有两行导致问题。

第一个在main函数中:

st.top = -1;

pushstack 函数中的第二个:

st->items[st->top++] = myEvent1;

这两行的作用是一样的:

st->items[-1] = myEvent1;

并且 -1 是数组的无效索引。

解决方法很简单:使用pre increment ++代替:

st->items[++st->top] = myEvent1;

这将首先将 st->top-1 增加到 0,并使用 0 作为索引。

函数定义相互矛盾。例如函数 popstack

void popstack(struct Stack* st) {
if (st->top == -1) {
    printf("Stack is empty");
    return;
}
    st->top--;
}

表示当 st->top == -1 时栈为空。另一方面,函数 emptystack(可能有错字,使用赋值运算符 = 而不是比较运算符 ==为空)

int emptystack(struct Stack* st) {
        return st->top = 0;
    }

表示当st->top等于0时栈为空。

或函数sizestack

int sizestack(struct Stack* st) {
        return st->top;
    }

表示大小等于值 st->top。很明显,由于声明

,堆栈的最大大小等于N
struct docEdit items[N];

但是函数pushstack

void pushstack(struct Stack* st, struct docEdit myEvent1) {
if (st->top == N - 1) {
    printf("Stack is full");
    return;
    }   
    
    st->items[st->top++] = myEvent1;
}

表示当st->top等于N - 1时堆栈已满。

也就是说,你应该决定数据成员top的初始值是否必须等于-10,并相应地调整所有函数定义。

至于函数 top 那么它应该 return 一个指向堆栈元素的指针。

struct docEdit * top( struct Stack* st) {
        if ( st->top != 0 )
        return st->items + st->top - 1;
        else
        return NULL; 
    }

使用 returned 指针,您可以更改堆栈顶部元素的值。在这个函数中,我假设当堆栈为空时 st->top 等于 0.