Класс стека шаблонов: в стеке нет данных

0

Функция pop() - это функция с ошибкой типа возвращаемого значения. Функция говорит, что возвращает объект Stack, но данные находятся в структуре узла. Как мне вернуть правильные данные?

Согласно моей функции отображения, похоже, что в стек не попадают данные.

Добавление newNode-> mData = данные и проверка с помощью отладки, похоже, что вещи попадают в стек. Кажется, проблема с отображением может быть проблемой.

Я также не уверен, что мои функции push и isExist правильные...

Отредактировано: pop push и isExist

/*      Pre:  The stack is initialized and searchKey is available
 *     Post:  The function retuns true if the searchKey exists in the queue;
 *            otherwise return false
 *  Purpose:  To determine if a given value exists in the stack or not
 *************************************************************************/
template <class T>
bool Stack<T>::isExist(T searchKey)
{
    bool exist = false;
    Node<T> *temp = mHead;

    if (mHead == NULL)
    {
        exist = false;
    }

        else if (temp->mData == searchKey)
        {
         exist = true;
        }

    else
    {
        while (temp->mNext != NULL)
        {
            if (temp->mData == searchKey)
            {
                exist = true;
                break;
            }

            temp = temp->mNext;
        }
    }

    return exist;
}


/*      Pre:  The stack is initialized
 *     Post:  The first node in the stack is removed, and its content is
 *            returned.  If the stack is empty return the default value
 *            for the given data type
 *  Purpose:  To remove the first node in the stack
 *************************************************************************/
template <class T>
T Stack<T>::pop()
{
    //Temp holds the mem location of the data
    //that will be popped/returned
    Node<T> *temp = mHead;

    if (mHead == NULL)
    {
        return NULL;
        cout << "The stack is empty!";
    }

    //Makes the next node in the stack the top one
    else if (mHead->mNext == NULL )
    {
        mHead = NULL;
        mTail = NULL;
    }

    else
    {
        mHead = mHead->mNext;
    }

    //Increment the counter down for the popped node
    mCount--;

    return temp->mData;
}


/*      Pre:  The stack is initialized
 *     Post:  The new node is added at the beginning of the stack.
 *            Duplication is allowed
 *  Purpose:  To add a new node at the beginning of the stack
 *************************************************************************/
template <class T>
void Stack<T>::push(T data)
{
    Node<T> *newNode = new Node<T>;
    newNode->mData = data;

    //If the stack is empty
    if (mHead == NULL && mTail == NULL)
    {
        mHead = newNode;
        mTail = newNode;
    }

    //Otherwise mHead will be the new node next node
    //The new node becomes the head
    else
    {
        newNode->mNext = mHead;
        mHead = newNode;
    }

    //Increment the counter to reflect the new node
    mCount++;
}

Функция отображения

template <class T>
void Stack<T>::display()
{
   Node<T> *tmp;

   if (isEmpty())
      cout << "Empty Stack\n";
   else
  {
      tmp = mHead;

      while (tmp != NULL)
      {
          cout << tmp->mData << " ";
          tmp = tmp->mNext;
       }
      cout << endl;
   }
}

Остальная часть класса стека

    #ifndef STACK_H
#define STACK_H

#include <iostream>

using namespace std;

template <class T>
class Stack {
   private:
       template <class T>
       struct Node
       {
          T       mData;
          Node<T> *mNext;

          /*      Pre:  None
           *     Post:  This object is initialized using default values
           *  Purpose:  To intialize date object
           *************************************************************************/
          Node()
          {
             mData = T();
             mNext = NULL;
          }


          /*      Pre:  None
           *     Post:  This object is initialized using specified data
           *  Purpose:  To intialize date object
           *************************************************************************/
          Node(T data)
          {
             mData = data;
             mNext = NULL;
          }
       };

      Node<T> *mHead, *mTail;
      int     mCount;

   public:
      Stack();
      ~Stack();

      int  getCount();

      void clear();
      void display();
      bool isEmpty();
      bool isExist(T searchKey);
      T    pop();
      void push(T data);
};


template <class T>
Stack<T>::Stack()
{
   mHead  = NULL;
   mTail  = NULL;
   mCount = 0;
}


template <class T>
Stack<T>::~Stack()
{
   while (!isEmpty())
      pop();
}


template <class T>
int Stack<T>::getCount()
{
   return mCount;
}


template <class T>
void Stack<T>::clear()
{
   while (!isEmpty())
      pop();
}


template <class T>
void Stack<T>::display()
{
   Node<T> *tmp;

   if (isEmpty())
      cout << "Empty Stack\n";
   else
   {
      tmp = mHead;

      while (tmp != NULL)
      {
         cout << tmp->mData << " ";
         tmp = tmp->mNext;
      }
      cout << endl;
   }
}


template <class T>
bool Stack<T>::isEmpty()
{
   return mCount == 0;
}



#endif
  • 1
    Не могли бы вы дать нам точную ошибку, которую дает вам ваш компилятор?
  • 0
    Я исправил ошибку, возвращая объект Stack <T> и используя -> для получения данных об элементе. Новая проблема заключается в том, что, согласно моей функции отображения, данные не попадают в стек.
Показать ещё 4 комментария
Теги:
templates
push
stack
pop

1 ответ

1

Вы не указали шаг в настройке данных!

template <class T>
void Stack<T>::push(T data)
{
    Node<T> *newNode = new Node<T>;
    //HERE! vv
    newNode->mData = data;
    //THERE! ^^

    //If the stack is empty
    if (mCount == 0)
    {
        mHead = newNode;
        mTail = newNode;
    }

    //Otherwise mHead will be the new node next node
    //The new node becomes the head
    else
    {
        newNode->mNext = mHead;
        mHead = newNode;
    }

    //Increment the counter to reflect the new node
    mCount++;
}

(Пользователь исправил текст зачеркивания в редактировании)

Другие вещи, о которых нужно подумать: что это mTail переменная mTail, и что должно с ней происходить?

Посмотрите на свою функцию isExist... Спросите себя, что произойдет, если вы нажмете номер, а затем спросите, существует ли это число? Будет ли он работать по назначению? Что произойдет, если вы попытаетесь выскочить из пустого стека? Что произойдет, если вы вызываете isExist в пустой стек?

  • 0
    Я все еще получаю тот же вывод всех 0, когда я добавил эту строку кода.
  • 0
    @Angel: Можете ли вы добавить код, чтобы показать свою функцию отображения? Также покажите нам свою функцию конструктора стека.
Показать ещё 4 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню