【问题标题】:Issues with a char stack implementation in c++?c++ 中的字符堆栈实现有问题吗?
【发布时间】:2020-10-14 10:46:56
【问题描述】:

我想实现一个字符堆栈实现,但我认为它有问题,因为当我尝试将它用于我的其他功能时,它没有单词和库堆栈工作。你能帮忙找出问题吗:

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

我想实现一个字符堆栈实现,但我认为它有问题,因为当我尝试将它用于我的其他功能时,它没有单词和库堆栈工作。你能帮忙找出一个问题吗: 提前谢谢!

【问题讨论】:

标签: c++ stack implementation


【解决方案1】:

我认为您需要对 pushpop 函数进行一些更改才能使您的 Stack 工作

  • push 中,您应该将arr[++t]=x; 放在if 语句之外而不是在内部,因为如果当前大小小于其容量而不是相等时,您想为arr 添加值

  • pop 中,您应该将arr[--t]; 放在if 语句之外而不是在内部,因为如果堆栈不为空,您想要删除并返回数组中的最后一个值。当它为空时,您应该考虑返回一个默认字符,例如空终止符\0。您还应该使用arr[t--] 而不是arr[--t],因为最后一个元素当前位于t,因此您希望它在降低其值之前评估arr[t] (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--];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 2016-12-16
    • 2019-12-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多