challenge
challenge

Reputation: 19

Issues with a char stack implementation in c++?

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!

Upvotes: 0

Views: 346

Answers (1)

VietHTran
VietHTran

Reputation: 2318

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--];
}

Upvotes: 1

Related Questions