编程实现判断程序中的括号是否匹配 () {} []

本文介绍了栈的数据结构,包括顺序栈和链式栈的实现,并详细阐述了如何利用栈来判断程序中的括号(() {} [])是否匹配,常见于面试题和操作系统中的函数调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "myhead.h"

//栈
struct stack
{
	char data;
	struct stack *next;
};


//初始化
struct stack *init()
{
	struct stack *p=malloc(sizeof(struct stack));
	p->next=NULL;
	
	return p;
}

//入栈
int push(struct stack *p,int n)
{
	struct stack *new=malloc(sizeof(struct stack));
	new->data=n;
	new->next=p->next;
	p->next=new;
}

//出栈
char pop(struct stack *p)
{
	struct stack *q=p->next;
	char n;
	if(p->next==NULL)
		return -1;
	n=p->next->data;
	p->next=p->next->next;
	free(q);

	return n;
}


int main()
{
	int i=0;
	char temp;
	char buf[200]="shfhd(hdfhfhdh)  fdjfjdjfj}   [fhdhsfhdsh (fdhsfh)";
	
	struct stack *filo=init();//栈初始化
	while(buf[i]!='\0')
	{
		if(buf[i]=='(' || buf[i]=='{' || buf[i]=='[')//入栈
		{
			push(filo,buf[i]);
			printf("%c 进栈!\n",buf[i]);
		}	
		
		if(buf[i]==')' || buf[i]=='}' || buf[i]==']')//出栈
		{
			temp=pop(filo);
			if(temp==-1)//栈内没有东西
				printf("没有东西可以出栈了!\n");
			else
				printf("%c 出栈!\n",temp);
			//判断3种括号是否匹配
			if('('!=temp && buf[i]==')')
				printf("%c 与前面不匹配!\n",buf[i]);
			if('['!=temp && buf[i]==']')
				printf("%c 与前面不匹配!\n",buf[i]);
			if('{'!=temp && buf[i]=='}')
				printf("%c 与前面不匹配!\n",buf[i]);
		}
		i++;//下一个字符
	}
	
	while(NULL!=filo->next)//全部出栈
	{
		printf("%c 后缺少与其匹配的字符!\n",pop(filo));
	}
	 
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值