匹配括号,C语言栈结构练习(附 逆波兰算法)

一个经典的栈结构练习题,输入一连串括号,匹配不同括号左右是否匹配。e.g.{【】()}是匹配的,而{(】】则因缺少相应的右括号不匹配。《C语言程序设计现代方法》第十章 编程题大题1

#include<stdio.h>
#include <string.h>

char* push(char cha, char* ptr);
char* pop(char* ptr);

int main()
{
	int 	i = 0;
	char 	braces[240];
	char  	stack[240] = {0};
	char 	*top;
	scanf("%s",braces);
	
	top = &stack[0];
	top = push (braces[i], top);
	i ++;								// push the first one

	for (;i < strlen(braces); i ++)	{ 	// fhuntion to push and estimate the bracket
		
		if (braces[i] == '}'){
			if (*top == '{'){			// if bracket is matche then del the matched one
				top = pop(top);
			}
		}
		else if (braces[i] == ']'){
			if (*top == '['){
				top = pop(top);
			}
		}
		else if (braces[i] == ')'){
			if (*top  == '('){
				top = pop(top);
			}
		}
		else {							// if not matche, push
			top = push (braces[i], top);
		}
		
	}

	if (top == &stack[0])				// if the pointer is in the bottom the stack is empty
		puts("matche");
	else
		puts("not matche");

	return 0;
}

char* push(char cha, char* ptr)
{
	ptr ++;
	*(ptr) = cha;

	return 	ptr;					//pointer go up and save the element on the top
}

char* pop(char* ptr)
{
	ptr --;
	
	return 	ptr; 					//pointer go down stack will ignore the previous element
}

附加一个 逆波兰算法 的代码,也用到了栈结构,逆波兰算法是一种非常贴合栈结构的算式语法。i.e.在读入句子过程中一旦取得算符就依算符处理前两个数字然后将得到的数字放在栈顶。

#include<stdio.h>
#include <string.h>
#include <ctype.h>

int* add(int* ptr);
int* sub(int* ptr);
int* pro(int* ptr);
int* div(int* ptr);
int* push(char cha, int* ptr);

int main()
{
	int 	i = 0;
	char 	expr[] = "612345+-**/3+";
	int  	stack[240] = {0};
	char 	*top;
	
	top = &stack[0];
	top = push (expr[i], top);
	i ++;

	for (;i < strlen(expr); i ++){
		
		if 		(expr[i] == '+')
			top = add(top);
		else if (expr[i] == '-')
			top = sub(top);
		else if (expr[i] == '*')
			top = pro(top);
		else if (expr[i] == '/')
			top = div(top);
		else if (isdigit)
			top = push (expr[i], top);
		else 
			break;
	}


	printf("result : %d",*top);

	return 0;
}

int* push(char cha, int* ptr)
{
	ptr ++;
	*(ptr) = cha - '0';

	return 	ptr;				
}

int* add(int* ptr)
{
	int i,j;
	
	i = *ptr;
	ptr --;
	j = *ptr;
	
	j = j + i;
	*ptr = j;
	
	return 	ptr;
}

int* sub(int* ptr)
{
	int i,j;
	
	i = *ptr;
	ptr --;
	j = *ptr;
	
	j = i - j;
	*ptr = j;
	
	return 	ptr;
}

int* pro(int* ptr)
{
	int i,j;
	
	i = *ptr;
	ptr --;
	j = *ptr;
	
	j = i * j;
	*ptr = j;
	
	return 	ptr;
}

int* div(int* ptr)
{
	int i,j;
	
	i = *ptr;
	ptr --;
	j = *ptr;
	
	j = i / j;
	*ptr = j;
	
	return 	ptr;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值