C数据结构理论和技术 - 同一堆栈中的ints和chars

Jos*_*ook 1 c data-structures

我正在努力将中缀表达式转换为前缀表达式,并决定使用堆栈来保存我的表达式.我正在使用链表方法来实现堆栈,并使用以下数据结构:

struct stacknode {
    char char_val;
    int int_val;
    struct stacknode *nextptr;
    struct stacknode *prevptr;
};
Run Code Online (Sandbox Code Playgroud)

然后我push()push_int()和写了两个不同的函数push_char().

push_int()分配的值'\0',以char_val然后将值被推到int_val.

push_char()分配的值-1,以int_val然后将值被推到char_val.

请注意,正在使用的所有整数值都大于0.

然后我编写了其余的函数来处理这样一个事实,即每个节点中的重要值可能是int或char,使用'\ 0'和-1的"否定"值来标识节点是否为"int" "节点或"char"节点.

从本质上讲,我想知道我是否认为数据结构都是错误的.有一个更好的方法吗?

Mic*_*son 6

虽然您的实现没有任何问题,但我认为使用带标记的联合可能更为惯用/显而易见.

然后你可以这样做:

struct StackValue
{
    _Bool is_int;
    union
    {
        char c;
        int i;
    } data;
};

struct StackNode
{
    struct StackValue data;
    struct StackNode *nextptr, *prevptr;
};
Run Code Online (Sandbox Code Playgroud)