c ++堆栈函数和错误处理

时间:2016-02-19 18:00:33

标签: c++ visual-c++

      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-&gt; next;

3 个答案:

答案 0 :(得分:0)

top=top->next;
如果topNULL

将失败,因此您应该在不执行函数中其余语句的情况下返回:

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

答案 1 :(得分:0)

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

时,您应该返回
var locations = "<%=Html.Raw(new JavascriptSerializer().Serialize(data)) %>";

希望这有助于。

答案 2 :(得分: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;
    }
}