2016-02-19 90 views
-1
 void pop() 
     { 
      //create new temp node 
      struct PersonNode *temp; 
      //if stack is empty 
      if(top==NULL) 
      { 
       cout<<"nThe stack is empty!!!"; // show message 
      } 
      temp=top; // store the top at temp 
      top=top->next; // make the top previous to current top 
      delete temp; // delete the temp (current top) 
     } 

这是我用来弹出堆栈的代码,除了当堆栈是空的,我尝试弹出它崩溃,我认为它由于这条线 top = top-> next;如果topNULLC++堆栈函数和错误处理

+2

如果你仍然做同样的事情,那么NULL检查是什么? – Michael

+1

你不需要'struct PersonNode * temp;'中额外的'struct',并且应该将它移到实际分配它的地方(或初始化为'nullptr')。 – crashmstr

+1

此外,您还需要一个'else'(如果堆栈为空,您*不会做出更改)。 – crashmstr

回答

0

这是你的代码清理了一下(只需在需要的地方声明temp并立即初始化,并防止在else子句的空栈上工作)。

void pop() 
{ 
    //if stack is empty, show message and stop 
    if(!top) 
    { 
     cout<<"nThe stack is empty!!!"; 
    } 
    else //else stack is not empty, pop 
    { 
     PersonNode *temp = top; 
     top = top->next; 
     delete temp; 
    } 
} 
0
top=top->next; 

会失败,所以你应该简单地返回而不执行语句的其余部分在功能:

if(top==NULL) { 
    cout<<"nThe stack is empty!!!"; // show message 
    return; // <<<<<<<<<<<<<< 
} 
+0

没有该代码该函数不再弹出 temp = top; //将顶部保存在温度为 top = top-> next; //使当前顶部的顶部前 删除临时; //删除temp(当前顶部) – Danny

+0

@Danny好吧,请发布[MCVE]。这可能有助于诊断您的真实问题。 –

+0

_“没有该代码,该函数不再弹出'temp = top';”_该分配不相关。 –

0

topNULL

if(top==NULL) 
    { 
     cout<<"nThe stack is empty!!!"; // show message 
     return;//You Should return from here 
    } 
您应该返回

希望这有助于。