题目:
思路:
代码:
#include
#include
#include
#include
typedef struct Stack
{
char* data;
int top;//栈顶元素坐标
int capacity;//栈的容量
}ST;
void STInit(ST* ps)
{
ps->data = NULL;
ps->top = 0;//ps->top=-1;
//初始化时top给0,意味着top指向栈顶数据的下一个
//初始化时top给1,意味着top指向栈顶数据
ps->capacity = 0;//初始化容量给0
}
void StackPush(ST* ps, char x)//压栈/入栈 *** 作
{
if (ps->capacity == ps->top)
{
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//三目 *** 作符
//如果ps->capacity等于0,那么就给4个字节的空间,如果不等于0就扩容两倍
char* tmp = (char*)realloc(ps->data, sizeof(char)*newCapacity);
if (tmp == NULL)//扩容失败退出程序
{
exit(-1);
}
ps->capacity = newCapacity;//把capacity换成新的
ps->data = tmp;//data也指向新的空间
}
ps->data[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)
{
ps->top--;
}
char StackTop(ST* ps)
{
return ps->data[ps->top - 1];
}
bool StackEmpty(ST* ps)
{
return ps->top == 0;//如果top等于0,返回true
}
int main()
{
char arr[100] = { 0 };
scanf("%s", arr);
getchar();
int n = strlen(arr);
ST List;
STInit(&List);
int flag = 0;
for (int i = 0; i < n; i++)
{
if (arr[i] == '[' || arr[i] == '(')
{
StackPush(&List, arr[i]);
}
else
{
if (StackEmpty(&List))
{
flag = 1;//为空时置为1
break;
}
else if (arr[i] == ']' && StackTop(&List) == '[')
{
StackPop(&List);
}
else if (arr[i] == ')' && StackTop(&List) == '(')
{
StackPop(&List);
}
else
{
flag = 1;//当右括号和左括号不匹配时置为1
break;
}
}
}
if (flag == 1 || List.top != 0)//栈不为空栈时或者flag=1时返回no
printf("NO");
else
printf("YES");
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)