【问题标题】:how can i solve the problem with stack in C?如何解决 C 中的堆栈问题?
【发布时间】:2021-07-23 20:22:45
【问题描述】:

我做了全局变量

struct node* top;
struct node {
    char x;
    struct node* next;
};

是结构节点

struct node* newnode(char x) {
    struct node* new1 = (struct node*)malloc(sizeof(struct node));
    new1->x = x;
    new1->next = NULL;
    return new1;
}

并且我初始化了top=NULL;

例如)推(顶部,a)

void push(struct node* h, char c) {
    struct node* new1 = newnode(c);

    if (count(h) > N) {
        printf("Stack FULL\n");
        return;
    }
    new1->next = h;
    h= new1;

}

那么top的地址值不应该是push函数后new1的地址值吗?

即使在push函数结束后,top仍然是NULL,所以我不知道该怎么办。

请给我一些建议!

【问题讨论】:

  • 这能回答你的问题吗? C Programming Stack
  • 不,这不是我的答案
  • 嗯?您可以在其他帖子中查看它们如何实现推送功能。
  • 感谢您的回答,但我想知道如何修复我的代码,我认为他的代码与我的不同
  • 注意:struct node { char x; struct node* next; }; 是一个结构体定义,而不是一个变量声明

标签: c pointers stack


【解决方案1】:

您正在传递top 中的,因此该函数无法更改top 中的内容。你可以传递一个指向top的指针,或者让函数返回你想要的top的新值,以便调用者可以将它分配给top

【讨论】:

  • 你的意思是我需要做一个指针传递到顶部?谢谢你的回答
  • 你可以传递一个指针 top,函数可以使用它来改变top的内容。
猜你喜欢
  • 2019-07-02
  • 2015-12-25
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 2014-08-06
  • 2015-12-18
  • 2012-12-06
相关资源
最近更新 更多