1

大家好,我的 C 代码有这个问题。我正在实现一个堆栈,每当我弹出它时,它都会更改函数 pop 中的堆栈,但不会更改原始堆栈。请帮忙。

这是我的代码

char pop(Node* top)
{
    char result ; 

    if (size == 0) // The stack is empty.
    {
        return '\0' ;
    }

    else //The stack contains at least one element .
    {
        result = top->opp ;
        top = top->next ;
    }

    size-- ;

    return result;
}
4

5 回答 5

0

尝试 char pop(Node** top) 并在 (*top) 上操作

于 2013-07-23T07:16:47.053 回答
0

请将顶部指针的引用发送到 pop 函数,如“char pop(Node **top) { }”并添加更改您的 else 块“top[0] = top[0]->next;” 而不是“top = top->next ;”。

于 2013-07-23T09:32:21.970 回答
0

您还需要释放 top 的当前位置...使用 free as

Node *ptr;

ptr = top;

if (size == 0) // The stack is empty.
    {
        return '\0' ;
    }

    else //The stack contains at least one element .
    {
        result = top->opp ;
        top = top->next ;
    }

    free(ptr); 

==================================================== ================

称它为

int main(){
 Node front = NULL:

 // place your code of PUSH here.

 pop(&front); // will call the function **pop**

}

}

于 2013-07-23T07:17:52.310 回答
0

我们需要更多代码,但我会尝试:

我猜你像这样使用这个函数:

char pop(Node* top)
{
    char result ; 

    if (size == 0) // The stack is empty.
    {
        return '\0' ;
    }

    else //The stack contains at least one element .
    {
        result = top->opp ;
        top = top->next ;
    }

    size-- ;

    return result;
}

int main()
{
   // this is the top of the stack
   Node    *stack; // let's say there already are some elements in this stack
   pop(stack);
   return 0;
}

问题是你要改变指针的值,然后stack会指向栈顶。为此,您必须使用指向指针的指针,如下所示:

char pop(Node** top)
{
    char result ; 
    Node *ptr;

    ptr = *top;
    if (size == 0) // The stack is empty.
    {
        return '\0' ;
    }

    else //The stack contains at least one element .
    {
        result = (*top)->opp ;
        (*top) = (*top)->next ;
        // You should free the pointer, like user2320537 said in his answer.
        free(ptr);
    }

    size-- ;

    return result;
}

int main()
{
   // this is the top of the stack
   Node    *stack; // let's say there already are some elements in this stack
   pop(&stack); // You give the pointer address
   return 0;
}
于 2013-07-23T07:19:26.200 回答
0

如果您更改变量的值,则将指针(其地址)传递给函数,例如

void increment(int *p) {
      p += 1;
}

类似于更改 POINTER 的值,您需要将指针传递给指向函数的指针

char pop(Node **top) {
       char t;
       Node  *p;
    if( size == 0 ) {
        return '\0';
    } else {
        p = *top;
        t = p->op;
        (*top) = (*top)-> next;
        free(p);
        return t;
    }
}
于 2013-07-23T09:24:14.273 回答