本文介绍了使用 C 将项目推入堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的推送函数,它接受一个堆栈和一个 int a 参数,将 int 转换为 stackNode 的一部分,并返回一个带有添加的新节点的新堆栈(StackNode 和 Stack 已经正确初始化):

this is my push function, which takes in a stack and an int a parameters, turns the int into part of a stackNode and returns a new stack with the added new node (StackNode and Stack have already been properly initialized):

Stack push(Stack stk,int data){
    struct StackNode *top = stk.top;
    struct StackNode *node;
    node->data = data;
    node->nextNode = top;
    stk.top = node;
    stk.count++;
    return stk;
}

我遇到的问题是,每次运行 push 函数时,它都会将堆栈中的其他 StackNode 项作为我运行的参数覆盖.

The problem I am having is that each time I run the push function, it over writes other StackNode items in the stack as the parameter I ran.

例如:

push(stk, 3): stack output = 3 //good so far
push (stk, 4): stack output= 4 4//the correct output would be 3 4!
push(stk, 56): stack out put= 56 56 56 //what's going on!

我做错了什么,请帮忙

推荐答案

您没有为节点分配内存.添加内存分配.

You did not allocate memory for the node. Add the memory allocation.

Stack push(Stack stk,int data){
    struct StackNode *top = stk.top;
    struct StackNode *node = malloc( sizeof( struct StackNode ) );

    node->data = data;
    node->nextNode = top;
    stk.top = node;
    stk.count++;

    return stk;
}

或者您可以添加成功分配的检查.

Or you can add a check of a successful allocation.

Stack push(Stack stk,int data){
    struct StackNode *top = stk.top;
    struct StackNode *node = malloc( sizeof( struct StackNode ) );

    if ( node != NULL )
    {
        node->data = data;
        node->nextNode = top;
        stk.top = node;
        stk.count++;
    }

    return stk;
}

我想最初 Stack 类型的对象的数据成员 top 被初始化为 NULL.

I suppose that initially the data member top of the object of the type Stack was initialized by NULL.

这篇关于使用 C 将项目推入堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 14:02
查看更多