1. 程式人生 > >C語言中綴轉字尾(棧的實現)

C語言中綴轉字尾(棧的實現)

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

#define maxsize 20

typedef struct st2 {
	int top;
	char str[maxsize];
}CharStackSize, *CharStack;

//初始化
void init(CharStack cstack)
{
	cstack->top = -1;
	return;
}

//判空


bool CharisEmpty(CharStack cstack)
{
	if (cstack->top == -1) {
		return true;
	}
	return false;
}

//判滿

bool CharisFull(CharStack cstack)
{
	if (cstack->top == maxsize - 1) {
		return true;
	}
	return false;
}
//出棧

bool CharPop(CharStack cstack, char * ch)
{
	if (CharisEmpty(cstack)) {
		return false;
	}
	*ch = cstack->str[cstack->top--];
	return true;
}
//進棧

bool CharPush(CharStack cstack, char ch)
{
	if (CharisFull(cstack)) {
		return false;
	}
	cstack->str[++cstack->top] = ch;
	return true;
}

int choose(char ch)
{
	if (ch == '+' || ch == '-') {
		return 1;
	}
	else if (ch == '*' || ch == '/') {
		return 2;
	}
	else if(ch  == ')'){
		return 3;
	}
	else if (ch == '(') {
		return 0;
	}
	else {
		return 0;
	}
}

int main(int argc, char *argv[])
{
	CharStack cstack = (CharStack)malloc(sizeof(CharStack));
	init(cstack);

	char biaodashi[50];
	gets_s(biaodashi, 50);

	for (int i = 0; i < strlen(biaodashi); i++) {
		if ('0' <= biaodashi[i] && biaodashi[i] <= '9') {
			printf("%c", biaodashi[i]);
		}
		//處理括號
		else if(biaodashi[i] == '(' ) {
			CharPush(cstack, biaodashi[i]);
		}
		else if (biaodashi[i] == ')') {
			CharPush(cstack, biaodashi[i]);
			while (cstack->top != -1) {
				char ch;
				CharPop(cstack, &ch);
				if(ch != '(' && ch != ')')
					printf("%c", ch);
				if (ch == '(') {
					break;
				}
			}
		}
		else {
			if (choose(biaodashi[i]) <= choose(cstack->str[cstack->top])) {
				while (cstack->top != -1) {
					char ch;
					CharPop(cstack, &ch);
					if (ch != '(' && ch != ')')
						printf("%c", ch);
					if (ch == '(') {
						break;
					}
					//9+(3-1)*3+6/2
				}
				CharPush(cstack, biaodashi[i]);
				//printf("%c", biaodashi[i]);
			}
			else {
				CharPush(cstack, biaodashi[i]);
			}
		}
	}
	while (cstack->top != -1) {
		char ch;
		CharPop(cstack, &ch);
		printf("%c", ch);
	}
	return 0;
}

輸出結果
在這裡插入圖片描述