Answer the question
In order to leave comments, you need to log in
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;
}
};
Answer the question
In order to leave comments, you need to log in
class secondStack
{
private:
stackElement *top = nullptr;
public:
bool isEmpty() { return !top; }
It is necessary to store in the class a pointer to the beginning of the stack and to the top
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;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question