数据结构2.2 - 栈和队列 应用

声明:大部分内容来自 - 《2019天勤数据结构高分笔记》

1. 栈

1.1 算术表达式中括号是否匹配,括号只有小括号

完整代码:

#include<bits/stdc++.h>
#define max 100
using namespace std;

void match(char s[])
{
	int flag = 1, i;
	char st[max];
	int top = -1;
	
	for(i = 0; s[i] != '\0'; i++)
	{
		if(s[i] == '(')
			st[++top] = '(';
		if(s[i] == ')')
		{
			if(top == -1)	
			{
				flag = 0;
				break;
			}
			else 
			{
				top--;
			}
		}
	}	
	if(flag == 1)
		cout << "括号匹配" << endl << endl;
	else
		cout << "括号不匹配!" << endl << endl;
		 
}

int main()
{
	char s[max]; 
		
	while(scanf("%s",s)!=EOF)
		match(s);
	
	return 0;
}

1.2 设计算法,求后缀表达式的数值,数值均为一位数,且为整数

完整代码:

#include<bits/stdc++.h>
#define max 100
using namespace std;

int op(int a, int b, char c)
{
	if(c == '+')
		return a + b;
	else if(c == '-')
		return a - b;
	else if (c == '*')
		return a*b;
	else if(c == '/' )
	{
		if(b == 0)
		{
			cout << "除以0错误!" << endl;
			return 0; 
		}
		else
			return a/b;
	}
}

void com(char s[])
{
	int st[max];
	int top  = -1, i;
	int a, b, c;
	
	for(i = 0; s[i] != '\0'; i++) 
	{
		if(s[i] >= '0' && s[i] <= '9')
			st[++top] = s[i] - '0';
		else
		{
			b = st[top--];
			a = st[top--];
			st[++top] = op(a, b, s[i]);
		}
	}
	cout << st[top] << endl << endl;
}

int main()
{
	char s[max];
	while(scanf("%s", s)!=EOF)
		com(s);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_1403034144

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值