用c ++弹出我的堆栈

时间:2014-12-04 03:54:56

标签: c++ stack push pop

所以我最后的课程是明天到期的,我已经用我的代码得到了这么多,它正确地加载了堆栈,我认为isEmpty函数正常工作,但我的函数没有弹出堆栈。只是说“弹出15”并没有继续。关于什么是错的任何想法?

/*
   Purpose of a program is to write a stack.cpp that will create a dynamic stack of int data type. 
 */


#include<iostream>
using namespace std;


struct StackNode
{
   int value;
   StackNode * next;
};

bool isEmpty(StackNode * top);
void displayStack(StackNode * top);
void push(StackNode *& top, int num);
void pop(StackNode *& top, int &item);

int main()
{
   StackNode * top = NULL;
   bool status;
   int item;


   // Push the values 5, 10, and 15
   // onto the stack.
   cout << "Pushing 5 \n";
   push(top, 5);
   cout << "Pushing 10 \n";
   push(top, 10);
   cout << "Pushing 15 \n";
   push(top, 15);

   cout << endl;
   cout << "Display the numbers in the stack (from top to bottom): ";
   displayStack(top);
   cout << endl;

   cout << "Popping... \n";
   pop(top, item);
   cout << item << endl;
   pop(top, item);
   cout << item << endl;
   pop(top, item);
   cout << item << endl;

   // The stack is empty, but try to 
   // pop another value.
   cout << "\nAttempting to pop again... ";
   pop(top, item);

   system("pause");
   return 0;
}

bool isEmpty(StackNode * top) // Checks to see if the whole stack is empty
{
   if (!top)
   {
      return false;
   }
}

void displayStack(StackNode * top) // Displays the stack
{
   if(top)
   {
      displayStack(top->next);
      cout << top->value << " ";
   }
}

void push(StackNode *& top, int num) // Pushes a number onto the stack
{
   if (!top)
   {
      top = new StackNode;
      top->value = num;
      top->next = NULL;
   }
   else
   {
      push(top->next, num);
   }
}

void pop(StackNode *& top, int &item) // clears the top number of the stack 
{
   if (top)
   {
      if (top->value)
      {
         item = top->value;
         pop(top->next, item);

      }
   }
}

1 个答案:

答案 0 :(得分:1)

push中存在逻辑错误。您的逻辑确保它将输入推送到堆栈的底部。

您需要的是:

void push(StackNode *& top, int num)
{
   StackNode* temp = new StackNode;
   temp->value = num;
   temp->next = top;
   top = temp;
}

pop也可以简化为:

void pop(StackNode *& top, int &item)
{
   if (top)
   {
      item = top->value;
      StackNode* temp = top;
      top = top->next;
      delete temp; // If you don't delete temp, it is a memory leak.
   }
}

isEmpty可以简化为:

bool isEmpty(StackNode * top)
{
   return (top == NULL);
}