c++ - 堆栈数据结构括号匹配
问题描述
我正在尝试这个括号匹配堆栈代码,每次我运行它只会给我括号不匹配我不知道出了什么问题。你们能帮我解决这个问题并告诉我如何进一步改进吗?这是在 c++ 中使用堆栈的正确方法吗,因为我是从使用 c 语言的源学习的。
#include<iostream>
using namespace std;
struct stack
{
int size;
int top;
char *arr;
};
int isEmpty(struct stack *ptr)
{
if(ptr->top==-1)
{
return 1;
}
return 0;
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size-1)
{
return 1;
}
return 0;
}
void push(struct stack *ptr,char val)
{
if(isFull(ptr))
{
cout<<"stack overflow"<<endl;
}
else
{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
char pop(struct stack *ptr)
{
if (isEmpty(ptr))
{
cout<<"stack underflow"<<endl;
return -1;
}
else
{
char val = ptr->arr[ptr->top];
ptr->top-1;
return val;
}
}
int parenthesisMatch (char * exp)
{
struct stack * sp = new struct stack;
sp->size = 80;
sp->top = -1;
sp->arr = new char(sp->size);
for(int i=0; exp[i]!='\0'; i++)
{
if (exp[i] == '(')
{
push(sp,'(');
}
else if(exp[i] == ')')
{
if (isEmpty(sp))
{
return 0;
}
pop(sp);
}
}
if (isEmpty(sp))
{
return 1;
}
return 0;
}
int main()
{
char *exp = "((8)(*--$$9))";
if(parenthesisMatch(exp))
{
cout<<"The parenthesis is matching\n";
}
else
{
cout<<"The parenthesis is not matching\n";
}
return 0;
}
解决方案
刚刚尝试调试代码,发现2个潜在错误:
- 正如@Welbog在评论中正确指出的那样,要创建一个数组,
sp->arr = new char[sp->size;
请在函数中使用parenthesisMatch()
。 - 在函数
pop()
中, 的值top
没有正确递减。
看看工作代码:
#include<iostream>
struct stack
{
int size;
int top;
char *arr;
};
int isEmpty(struct stack *ptr)
{
if(ptr->top==-1)
{
return 1;
}
return 0;
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size-1)
{
return 1;
}
return 0;
}
void push(struct stack *ptr,char val)
{
if(isFull(ptr))
{
std::cout<<"stack overflow"<<std::endl;
}
else
{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
char pop(struct stack *ptr)
{
if (isEmpty(ptr))
{
std::cout<<"stack underflow"<<std::endl;
return -1;
}
else
{
char val = ptr->arr[ptr->top];
ptr->top-=1;
return val;
}
}
int parenthesisMatch (char * exp)
{
struct stack * sp = new struct stack;
sp->size = 80;
sp->top = -1;
sp->arr = new char[sp->size];
for(int i=0; exp[i]!='\0'; i++)
{
if (exp[i] == '(')
{
push(sp,'(');
}
else if(exp[i] == ')')
{
if (isEmpty(sp))
{
return 0;
}
pop(sp);
}
}
if (isEmpty(sp))
{
return 1;
}
return 0;
}
int main()
{
char *exp = "((8)(*--$$9))";
if(parenthesisMatch(exp))
{
std::cout<<"The parenthesis is matching\n";
}
else
{
std::cout<<"The parenthesis is not matching\n";
}
return 0;
}
推荐阅读
- json - 在 Python 3.6 JSON 模块中,为什么我必须同时使用加载和加载?
- python-3.x - 自动输入命令提示符
- python - 大于 RAM 的 Numpy 数组:写入磁盘还是核外解决方案?
- machine-learning - Keras Adam 优化器学习率超参数与单独计算的网络参数学习率有何关系?
- json - 尝试从 Bash 中的 JSON 文件加载消息负载以发送到 Slack 通道
- testing - 当配置为不运行时,带有标签的功能仍在运行
- bash - curl api 请求中的变量
- printing - ZPL 语言 - 无法旋转标签
- java - 如何使用具有多个 bean 定义的 Spring ObjectProvider
- java - 使用动态规划解决问题