V
V
Vlad Timofeev2016-03-21 16:41:30
Programming
Vlad Timofeev, 2016-03-21 16:41:30

How to check if the stack is empty?

Good day.
I am making a stack with Linked Lists and classes in C ++, let's say there is a class of a stack element and a class of the stack itself. At the very beginning, we create 1 stack element "top" (it is still the top one) using the constructor with the fields key = NULL, deeperElement = NULL;
And now I want to make an isEmpty method on the stack, but comparing NULL and a numeric type is stupid.
It's probably better to throw the code:

class stackElement
  {
  private:
    int key;
    stackElement *deeper;
  public:
    stackElement()
    {
      key = NULL;
      deeper = NULL;
    }
    
    void setDeeper(stackElement *d)
    {
      deeper = d;
    }

    stackElement* getDeeper() const
    {
      return deeper;
    }

    void setValue(int value)
    {
      key = value;
    }
    int getValue() const
    {
      return key;
    }
  };


  class secondStack
  {
  private:
    stackElement *top;
  public:
    void Push(int n)
    {
      stackElement *temp = new stackElement;
      temp->setValue(n);
      temp->setDeeper(top);
      top = temp;
    }

    int Pop()
    {
      int deletedInteger = top->getValue();
      stackElement *temp = top;
      top = top->getDeeper();
      delete temp;
      return deletedInteger;
    }

    bool isEmpty()
    {
// дураку ясно, что если верхнему элементу стэка присвоить значение 0, то работать это не будет
      if (top->getValue() == NULL)
        return true;
      return false;
    }
  };

Actually how to do this check? Maybe some other constant instead of NULL ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
AtomKrieg, 2016-03-21
@PyTiMa

class secondStack
{
  private:
    stackElement *top = nullptr;
  public:
   bool isEmpty() { return !top; }

V
Valentin Lukyanets, 2016-03-21
@commander_spock

It is necessary to store in the class a pointer to the beginning of the stack and to the top

A
abcd0x00, 2016-03-23
@abcd0x00

At the very beginning, we create 1 stack element "top" (it is also the top one for now) using the constructor with the fields key = NULL, deeperElement = NULL;

Why is it needed there if there is nothing in it? It happens that they teach like this in universities, adding extra unnecessary elements.
Make a stack and initialize its top with a null pointer and check by this value. No pointer to an object can be equal to a null pointer, so it's a safe bet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question