1

こんにちは、私の C コードでこの問題が発生しました。私はスタックを実装していますが、ポップすると関数 pop のスタックが変更されますが、元の stack は変更されません。助けてください。

ここに私のコードがあります

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)
{
    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

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) { }" のような pop 関数へのトップ ポインタの参照を送信し、else ブロックの変更 "top[0] = top[0]->next;" を追加してください。"top = top->next ;" の代わりに。

于 2013-07-23T09:32:21.970 に答える
0

char pop(Node** top) を試して (*top) を操作する

于 2013-07-23T07:16:47.053 に答える