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

数据结构 C 代码 、括号匹配、表达式求值

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

数据结构 C 代码 、括号匹配、表达式求值

数据结构 C 代码 栈、括号匹配、表达式求值 栈的定义
  • 栈是一个特殊的线性表,是限定于仅在一端(通常是表尾)进行插入和删除操作的线性表,由于栈的操作具有后进先出的固有特性,使得栈成为程序设计中的有用工具。另外,如果问题求解的过程具有"后进先出"的天然特性的话,则求解的算法中也必须利用栈。
栈的操作示意图
  • 入栈

  • 出栈

栈相关操作的实现
#include 
#include 

#define STACK_MAX_SIZE 10

//结构体的定义
typedef struct CharStack {
    int top;

    int data[STACK_MAX_SIZE]; 
} *CharStackPtr;

//栈的初始化
CharStackPtr charStackInit() {
	CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(CharStack));
	resultPtr->top = -1;

	return resultPtr;
}


//依次对栈中的每个数据元素输出
void outputStack(CharStackPtr paraStack) {
    for (int i = 0; i <= paraStack->top; i ++) {
        printf("%c ", paraStack->data[i]);
    }
    printf("rn");
}

//进栈操作
void push(CharStackPtr paraStackPtr, int paraValue) {
    if (paraStackPtr->top >= STACK_MAX_SIZE - 1) {
        printf("Cannot push element: stack full.rn");
        return;
    }

	paraStackPtr->top ++;

    paraStackPtr->data[paraStackPtr->top] = paraValue;
}

//出栈操作
char pop(CharStackPtr paraStackPtr) {
    if (paraStackPtr->top < 0) {
        printf("Cannot pop element: stack empty.rn");
        return '';
    }

	paraStackPtr->top --;

    return paraStackPtr->data[paraStackPtr->top + 1];
}

//测试代码
void pushPopTest() {
    printf("---- pushPopTest begins. ----rn");

    CharStackPtr tempStack = charStackInit();
    printf("After initialization, the stack is: ");
	outputStack(tempStack);

	for (char ch = 'a'; ch < 'm'; ch ++) {
		printf("Pushing %c.rn", ch);
		push(tempStack, ch);
		outputStack(tempStack);
	}

	for (int i = 0; i < 3; i ++) {
		ch = pop(tempStack);
		printf("Pop %c.rn", ch);
		outputStack(tempStack);
	}

    printf("---- pushPopTest ends. ----rn");
}


void main() {
	pushPopTest();
}

利用栈解决括号匹配问题
#include 
#include 

#define STACK_MAX_SIZE 10

//定义结构体
typedef struct CharStack {
    int top;

    int data[STACK_MAX_SIZE]; 
} *CharStackPtr;

//栈的初始化
CharStackPtr charStackInit() {
	CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(struct CharStack));
	resultPtr->top = -1;

	return resultPtr;
}

//依次对栈中的每个数据元素输出
void outputStack(CharStackPtr paraStack) {
    for (int i = 0; i <= paraStack->top; i ++) {
        printf("%c ", paraStack->data[i]);
    }
    printf("rn");
}

//进栈操作
void push(CharStackPtr paraStackPtr, int paraValue) {
    if (paraStackPtr->top >= STACK_MAX_SIZE - 1) {
        printf("Cannot push element: stack full.rn");
        return;
    }

	paraStackPtr->top ++;

    paraStackPtr->data[paraStackPtr->top] = paraValue;
}

//出栈操作
char pop(CharStackPtr paraStackPtr) {
    if (paraStackPtr->top < 0) {
        printf("Cannot pop element: stack empty.rn");
        return '';
    }

	paraStackPtr->top --;

    return paraStackPtr->data[paraStackPtr->top + 1];
}

//测试
void pushPopTest() {
    printf("---- pushPopTest begins. ----rn");

    CharStackPtr tempStack = charStackInit();
    printf("After initialization, the stack is: ");
	outputStack(tempStack);

	for (char ch = 'a'; ch < 'm'; ch ++) {
		printf("Pushing %c.rn", ch);
		push(tempStack, ch);
		outputStack(tempStack);
	}

	for (int i = 0; i < 3; i ++) {
		ch = pop(tempStack);
		printf("Pop %c.rn", ch);
		outputStack(tempStack);
	}

    printf("---- pushPopTest ends. ----rn");
}

//匹配函数
bool bracketMatching(char* paraString, int paraLength) {
    CharStackPtr tempStack = charStackInit();
	push(tempStack, '#');
	char tempChar, tempPopedChar;

	for (int i = 0; i < paraLength; i++) {
		tempChar = paraString[i];

		switch (tempChar) {
		case '(':
		case '[':
		case '{':
			push(tempStack, tempChar);
			break;
		case ')':
			tempPopedChar = pop(tempStack);
			if (tempPopedChar != '(') {
				return false;
			}
			break;
		case ']':
			tempPopedChar = pop(tempStack);
			if (tempPopedChar != '[') {
				return false;
			}
			break;
		case '}':
			tempPopedChar = pop(tempStack);
			if (tempPopedChar != '{') {
				return false;
			} 
			break;
		default:
			break;
		}
	}

	tempPopedChar = pop(tempStack);
	if (tempPopedChar != '#') {
		return true;
	}

	return true;
}

//测试代码
void bracketMatchingTest() {
	char* tempExpression = "[2 + (1 - 3)] * 4";
	bool tempMatch = bracketMatching(tempExpression, 17);
	printf("Is the expression '%s' bracket matching? %d rn", tempExpression, tempMatch);


	tempExpression = "( )  )";
	tempMatch = bracketMatching(tempExpression, 6);
	printf("Is the expression '%s' bracket matching? %d rn", tempExpression, tempMatch);

	tempExpression = "()()(())";
	tempMatch = bracketMatching(tempExpression, 8);
	printf("Is the expression '%s' bracket matching? %d rn", tempExpression, tempMatch);

	tempExpression = "({}[])";
	tempMatch = bracketMatching(tempExpression, 6);
	printf("Is the expression '%s' bracket matching? %d rn", tempExpression, tempMatch);


	tempExpression = ")(";
	tempMatch = bracketMatching(tempExpression, 2);
	printf("Is the expression '%s' bracket matching? %d rn", tempExpression, tempMatch);
}

void main() {
	// pushPopTest();
	bracketMatchingTest();
}

表达式求值
  • isdigit是计算机C(C++)语言中的一个函数,主要用于检查其参数是否为十进制数字字符。

    函数定义:int isdigit(int c);

  • unordered_map是一种关联容器,存储基于键值和映射组成的元素,即key-value。允许基于键快速查找元素。在unordered_map中,键值唯一标识元素,映射的值是一个与该对象关联的内容的对象。

  • auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型.

//202031061018 刘知鑫
#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;
}

        {
            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/873015.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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