Visual C++ 堆栈函数和错误处理

visual c++ stack functions and error handleing

本文关键字:错误 处理 函数 C++ 堆栈 Visual      更新时间:2023-10-16
      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)
      }
这是我用来弹出堆栈的代码,

它有效,除非堆栈为空并且我尝试弹出它崩溃,我认为这是由于这一行顶部 = 顶部>下一个;

这是

你的代码清理了一点(只在需要时声明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;
    }
}
top=top->next;

如果top NULL,将失败,因此您应该简单地返回而不执行函数中的其余语句:

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

您应该在top NULL时返回

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

希望这有帮助。