C链表 - 不允许指向不完整类的指针

时间:2016-02-03 16:29:40

标签: c++ linked-list char visual-studio-2015 stack

我正在尝试实现一个包含char类型链接列表的堆栈。当我尝试返回顶部节点中找到的值时,它会给出上面的错误。

代码:

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "header4AB.h"

typedef struct {
    struct node_t * top;
    int max_size;
    int used_size;
} Stack;

typedef struct node {
    int val;
    struct node * next;
}node_t;


Stack * stack(int max_size) {
    Stack * S = malloc(sizeof(Stack));
    S->top = NULL;
    S->max_size = max_size;
    S->used_size = 0;
    return S;
}

bool push(Stack * S, char p) {
    if (S->used_size != S->max_size) {
            node_t * temp = malloc(sizeof(node_t));
            temp->val = p;
            temp->next = S->top;
            S->top = temp;
            S->used_size++;
        return true;
    }
    return false;
}

bool pop(Stack * S) {
    node_t * temp;
    if (S->top == NULL)
        return false;
    temp = S->top;
    S->top = temp->next;
    free(temp);

    return true;
}

char top(Stack * S) {
    if (S->top != NULL) {
        return S->top->val; //error here
    }
}

我对固定大小的堆栈中的链接列表的概念很新,我还没有测试过我的代码,所以我不知道它是否有效。任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:2)

结构必须像

typedef struct node {
    int val;
    struct node * next;
}node_t;

typedef struct {
    node_t * top;
    int max_size;
    int used_size;
} Stack;

或者

struct node {
    int val;
    struct node * next;
};

typedef struct {
    struct node * top;
    int max_size;
    int used_size;
}Stack;

Stack * stack(int max_size) {
    Stack * S = malloc(sizeof(Stack));
    S->top = NULL;
    S->max_size = max_size;
    S->used_size = 0;
    return S;
}

bool push(Stack * S, char p) {
    if (S->used_size != S->max_size) {
            struct node * temp = malloc(sizeof(struct node));
            temp->val = p;
            temp->next = S->top;
            S->top = temp;
            S->used_size++;
        return true;
    }
    return false;
}

bool pop(Stack * S) {
    struct node * temp;
    if (S->top == NULL)
        return false;
    temp = S->top;
    S->top = temp->next;
    free(temp);

    return true;
}

char top(Stack * S) {
    if (S->top != NULL) {
        return S->top->val; //error here
    }
}

答案 1 :(得分:0)

typedef struct {
    struct node_t * top;   //Here you are using node_t type. To use this you must define this before. This causes you error.
    int max_size;
    int used_size;
} Stack;

要解决:

node_t使用它之前声明Stack

答案 2 :(得分:0)

您的代码中未定义struct node_t。使用struct nodenode_t,或将所有node_t更改为node

在language-legalese中,typedef名称和struct标签位于不同的名称空间中。 Xstruct X无关(除非程序恰好typedef struct X X)。