栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构--表达式括号匹配和运算

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构--表达式括号匹配和运算

 多项式括号匹配:

#include 
#include 

#define STACK_MAX_SIZE 10

//创建栈结构体 
typedef struct charStack{
	int top;
	
	int data[STACK_MAX_SIZE];
}*stackPtr; 

//输出栈
void outputStack(stackPtr paraStack){
	for(int i=0;i<=paraStack->top;i++){
		printf("%d ",paraStack->data[i]);
	}
	printf("rn");
} 

//初始化栈
stackPtr initStack(){
	stackPtr tempStack=(stackPtr)malloc(sizeof(stackPtr));
	tempStack->top=-1;
	
	return tempStack;
} 

//入栈
void push(stackPtr stack,int paraValue){
	//检查空间
	 if (stack->top >= STACK_MAX_SIZE - 1) {
        printf("Cannot push element: stack full.rn");
        return;
    }
    
    //update top
	stack->top++;
	
	//添加元素
	 stack->data[stack->top]=paraValue; 
} 

//出栈
int pop(stackPtr stack){
    // 空间检查 
    if (stack->top < 0) {
        printf("Cannot pop element: stack empty.rn");
        return '';
    }
    
	//update top
	stack->top--;
	
	//返回栈顶 
	return stack->data[stack->top+1];
} 

bool bracketMatch(char *paraString, char paraLength){
	//初始化创建栈底
	 stackPtr tempStack= initStack();
	 push(tempStack, '#');
	 char tempChar,tempPopedChar;
	  
	//start
	for(int i=0;i 

运行结果:

 多项式加法:

#include 
#include 
#include 
#include 
#include 

using namespace std;

stack num;
stack op;

void eval()
{
    auto b = num.top();
    num.pop();
    auto a = num.top();
    num.pop();
    auto c = op.top();
    op.pop();
    int x;
    if (c == '+') x = a + b;
    else if (c == '-') x = a - b;
    else if (c == '*') x = a * b;
    else x = a / b;
    num.push(x);
}

int main()
{
    unordered_map pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
    string str;
    cin >> str;
    for (int i = 0; i < str.size(); i ++ )
    {
        auto c = str[i];
        if (isdigit(c))
        {
            int x = 0, j = i;
            while (j < str.size() && isdigit(str[j]))
                x = x * 10 + str[j ++ ] - '0';
            i = j - 1;
            num.push(x);
        }
        else if (c == '(') op.push(c);
        else if (c == ')')
        {
            while (op.top() != '(') eval();
            op.pop();
        }
        else
        {
            while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval();
            op.push(c);
        }
    }
    while (op.size()) eval();
    cout << num.top() << endl;
    return 0;
}

运行结果:

 总结:

括号匹配还好,表达式运算确实难到我了,没办法,又分析了一下大佬的代码,总结如下:
当自己在写代码时,总是想到哪里就写到哪里,其实说白了,还是自己的思维逻辑不是很清晰很明了,自己在以后必须多加强自己的思维逻辑训练,不能让自己的思维总是“旋转跳跃”。
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/869469.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号