0

I want to make a char stack implementation, but i think something is wrong with it because when i try to use it for my other function it does not word and library stack works. Can you help to find an issue:

using namespace std;



Stack::Stack(int size)
{
    arr = new char[size];
    capacity = size;
    t = -1;
}

int Stack::size()
{
    return (t + 1);
}

Stack::~Stack()
{
    delete[] arr;
}

bool Stack::empty()
{
    return size()==0;   
}


void Stack::push(char x) 
{
    if (size()==capacity) {
        cout<<"Push  to full stack";
    arr[++t]=x;
    }
}


char Stack::pop() 
{
    if (empty()) {
        cout<<"Pop from empty  stack";
    --t;
    }
    return 0;
}
char Stack::top()
{
    if (!empty())
        return arr[t];
    else
        cout<<"Top of the stack is empty";
    return  0;
    
}

I want to make a char stack implementation, but i think something is wrong with it because when i try to use it for my other function it does not word and library stack works. Can you help to find an issue: Thank you in advance!

  • First of all "it doesn't work" is not a good description of your problem. *How* isn't it working? When you do something, what is supposed to happen? What actually happens? Please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Also learn how to [edit] your questions to improve them, like including a [mcve]. – Some programmer dude Oct 14 '20 at 10:51
  • As a possible hint, please do some [rubber duck debugging](https://en.wikipedia.org/wiki/Rubber_duck_debugging) of your `pop` function (and pay close attention to your blocks and scope). – Some programmer dude Oct 14 '20 at 10:51

1 Answers1

1

I think you need to make some changes to the push and pop function for your Stack to work

  • In push, you should put arr[++t]=x; outside the if statement instead of inside as you want to add value to arr if the current size is less than its capacity instead of when it is equal

  • In pop, you should put arr[--t]; outside the if statement instead of inside as you want to remove and return the last value in the array if the stack is not empty. When it is empty, you should consider returning a default character such as the null terminator character \0. You should also want to use arr[t--] instead of arr[--t] as the last element is currently at t so you want it to evaluate arr[t] before decreasing its value (t--)

void Stack::push(char x)
{
    if (size()==capacity) {
        cout<<"Push  to full stack";
        return;
    }
    arr[++t]=x;
}


char Stack::pop()
{
    if (empty()) {
        cout<<"Pop from empty  stack";
        return '\0';
    }
    return arr[t--];
}

VietHTran
  • 2,233
  • 2
  • 9
  • 16