我們需要更多的代碼,但我會嘗試:
我猜你使用該功能是這樣的:
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;
}
通過查看代碼,我建議你做一些編輯1.你不會刪除在開始時傳給你的'top',所以它是內存泄漏,2.因爲它是堆棧,你不需要'size' ,你可以簡單地檢查'if(top!= NULL)'表示堆棧不是空的... – Opsenas