【数据结构】之栈的应用——有效的括号

文章目录

有效的括号

原题链接:有效的括号
在这里插入图片描述
在这里插入图片描述
详解栈的链接
这道题可以利用栈来解决

1.左括号入栈
2.右括号与出栈顶左括号匹配

//创建一个动态的栈
typedef char STDateType;
typedef struct Stack
{
	STDateType* a;//储存指定数据类型的数组
	int top;//栈顶
	int capacity;//栈的容量
}ST;

//栈的初始化和销毁
void STInit(ST* pst);
void STDestroy(ST* pst);

//入栈和出栈
void STPush(ST* pst, STDateType x);
void STPop(ST* pst);

//返回栈顶数据
STDateType STTop(ST* pst);

//判空
bool STEmpty(ST* pst);

//栈数据个数
int STSize(ST* pst);

//栈的初始化
void STInit(ST* pst)
{
	assert(pst);
	pst->a = NULL;
	//指向栈顶元素的下一个位置
	pst->top = 0;

	//指向栈顶元素
	//pst->top = -1;

	pst->capacity = 0;
}

//栈的销毁
void STDestroy(ST* pst)
{
	assert(pst);
	free(pst->a);
	pst->a = NULL;
	pst->top = 0;
	pst->capacity = 0;
}

//入栈
void STPush(ST* pst, STDateType x)
{
	assert(pst);
	//如果容量不够,需要扩容
	if (pst->top == pst->capacity)
	{
		int newcapacity = pst->capacity == 0 ? 4 : 2 * pst->capacity;
		STDateType* tmp = (STDateType*)realloc(pst->a, newcapacity * sizeof(ST));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		pst->a = tmp;
		pst->capacity = newcapacity;
	}
	//储存数据
	pst->a[pst->top++] = x;
}

//出栈
void STPop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);
	pst->top--;
}

//返回栈顶数据
STDateType STTop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);
	return pst->a[pst->top - 1];
}

//判空
bool STEmpty(ST* pst)
{
	assert(pst);
	return pst->top == 0;
}

//栈数据个数
int STSize(ST* pst)
{
	assert(pst);
	return pst->top;
}

bool isValid(char* s)
{
    //定义一个栈
    ST st;
    STInit(&st);
    while(*s)
    {
        //左括号入栈
        if(*s == '(' || *s == '[' || *s == '{')
        {
            STPush(&st,*s);
        }
        //右括号与出栈的左括号匹配
        else
        {
            if(STSize(&st) == 0)
            {
                STDestroy(&st);
                return false;
            }
            char top = STTop(&st);
            STPop(&st);
            if((top == '(' && *s != ')') ||( top == '[' && *s != ']') || (top == '{' && *s != '}'))
            {
                STDestroy(&st);
                return false;
            }
        }
        s++;
    }
    //出循环后有两种情况:
    //左括号 == 右括号    
    //左括号的数量多于右括号的数量
    bool ret = STEmpty(&st);
    STDestroy(&st);
    return ret;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值