数据结构与算法_C语言栈型应用案例_就近括号匹配

#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

/****************************************************
*		1	栈的应用案例 - 就近匹配						*
*		1.1	从第一个字符开始扫描						*
*		1.2	如果是左括号,入栈							*
*		1.3	如果是右括号								*
*		1.3.1	如果栈中元素大于 0   -- - 出栈			*
*		1.3.2	如果是空栈   立即停止  报错				*
*		1.4	当所有字符都扫描结束后						*
*		1.4.1	栈为空	 --  没有错误					*
*		1.4.2	栈不为空-- - 报错						*
****************************************************/

//********************栈型数据结构********************
//设计栈 结构体
#define MAX 1024
typedef struct __SSTACK
{
	void*data[MAX];
	int m_Size;
}SeqStack;

//对外隐身结构体属性
typedef void* SStack;

//初始化栈结构体
SStack init_SeqStack()
{
	SeqStack*p = malloc(sizeof(SeqStack));
	if (p == NULL)
	{
		return NULL;
	}
	memset(p, 0, sizeof(SeqStack));
	return p;
}
//入栈
void push_SeqStack(SStack handle, void*data)
{
	if (handle == NULL || data == NULL)
	{
		return;
	}
	SeqStack*p = handle;
	if (p->m_Size == MAX)
	{
		return;
	}
	p->data[p->m_Size] = data;
	p->m_Size++;
}
//出栈
void pop_SeqStack(SStack handle)
{
	if (handle == NULL)
	{
		return;
	}
	SeqStack*p = handle;
	p->m_Size--;
	p->data[p->m_Size] = NULL;
}
//返回栈顶
void* top_SeqStack(SStack handle)
{
	if (handle == NULL)
	{
		return;
	}
	SeqStack*p = handle;
	return p->data[--p->m_Size];
}
//返回元素个数
int size_SeqStack(SStack handle)
{
	if (handle == NULL)
	{
		return -1;
	}
	SeqStack*p = handle;
	return p->m_Size;
}
//判断是否为空
int isEmpty_SeqStack(SStack handle)
{
	if (handle == NULL)
	{
		return -1;
	}
	SeqStack*p = handle;
	if (p->m_Size == 0)
	{
		return 1;
	}
	return 0;
}
//销毁栈
void destory_SeqStack(SStack handle)
{
	if (handle == NULL)
	{
		return -1;
	}
	SeqStack*p = handle;
	free(p);
}
//********************用户区********************
void print_Error(const char*error,const char*p,const char*cur_pos)
{
	printf("%s\n", error);
	printf("%s\n", p);
	int num = cur_pos - p;
	for (int i = 0; i < num;i++)
	{
		printf(" ");
	}
	printf("A\n");
}

void test()
{
	char*str = "(5+10)*10-(+(5+1*90(";
	char*p = str;
	SStack handle = init_SeqStack();
	while (*p != '\0')
	{
		if (*p=='(')
		{
			push_SeqStack(handle, p);
		}
		if (*p==')')
		{
			if (isEmpty_SeqStack(handle))
			{
				print_Error("右括号匹配失败", str, p);
				break;
			}
			pop_SeqStack(handle);
		}
		p++;
	}
	while (!isEmpty_SeqStack(handle))
	{
		char*p = top_SeqStack(handle);
		print_Error("左括号匹配失败", str, p);
	}
	destory_SeqStack(handle);
}

int main()
{
	test();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值