通过栈将中缀表达式转换为后缀表达式并根据后缀表达式求解,包含的Header.h为之前发过的栈操作相关函数实例程序,改成头文件就行。练习+记录,高手无视。
OutPut:
The init formula:3+4*5+(6*7+8)*9
The stack is empty.
Convert result:345*+67*8+9*+
Calculate result:473
//Code by Pnig0s1992 //Date:2012,3,21 #include <stdio.h> #include <Windows.h> #include "Header.h" #define MAXLENGTH 50 VOID ConvertAndCalc(LPSTR lpContainer,Stack S); int Caculate(LPSTR lpContainer,Stack S); int getOptPriv(CHAR cOpt); int main(int argc,char **argv) { LPSTR lpContainer = "3+4*5+(6*7+8)*9"; Stack myStack = CreateStack(); printf("\nThe init formula:%s",lpContainer); ConvertAndCalc(lpContainer,myStack); system("pause"); return 0; } int getOptPriv(CHAR cOpt) { switch(cOpt) { case '(': return 7; case ')': return 7; case '*': return 5; case '/': return 5; case '+': return 3; case '-': return 3; default: return 0; } } VOID ConvertAndCalc(LPSTR lpContainer,Stack S) { LPSTR lpResult = (LPSTR)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,MAXLENGTH); LPSTR lpTemp = (LPSTR)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,MAXLENGTH); while(*lpContainer != '\0') { if(isalnum(*lpContainer)) { sprintf(lpTemp,"%c",*lpContainer); strcat(lpResult,lpTemp); ZeroMemory(lpTemp,MAXLENGTH); }else { if(isEmpty(S)) { Push(*lpContainer,S); }else if (*lpContainer == ')') { while(!isEmpty(S) && getTop(S) != '(') { sprintf(lpTemp,"%c",Pop(S)); strcat(lpResult,lpTemp); ZeroMemory(lpTemp,MAXLENGTH); } Pop(S); }else { if(getOptPriv(getTop(S)) < getOptPriv(*lpContainer)) { Push(*lpContainer,S); }else { while((!isEmpty(S)) && (getOptPriv(getTop(S)) >= getOptPriv(*lpContainer)) && getTop(S) != '(') { sprintf(lpTemp,"%c",Pop(S)); strcat(lpResult,lpTemp); ZeroMemory(lpTemp,MAXLENGTH); } Push(*lpContainer,S); } } } lpContainer++; } while(!isEmpty(S)) { sprintf(lpTemp,"%c",Pop(S)); strcat(lpResult,lpTemp); ZeroMemory(lpTemp,MAXLENGTH); } MakeEmpty(S); printf("\nConvert result:%s",lpResult); int iResult = Caculate(lpResult,S); printf("\nCalculate result:%d",iResult); return; } int Caculate(LPSTR lpContainer,Stack S) { int iTemp; int iResult; while(*lpContainer != '\0') { if(isdigit(*lpContainer)) { LPSTR lpTemo = (LPSTR)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,MAXLENGTH); sprintf(lpTemo,"%c",*lpContainer); Push(atoi((const char *)lpTemo),S); }else { switch(*lpContainer) { case '+': Push(Pop(S)+Pop(S),S); break; case '-': Push(Pop(S)-Pop(S),S); break; case '*': Push(Pop(S)*Pop(S),S); break; case '/': Push(Pop(S)/Pop(S),S); break; default: break; } } lpContainer++; } return Pop(S); }
本文出自 “About:Blank H4cking” 博客,请务必保留此出处http://pnig0s1992.blog.51cto.com/393390/812563
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索return
, 表达式
, 中缀表达式
, case
, pop
, 表达式后缀
, 后缀表达式
maxlength
中缀表达式求值、java中缀表达式求值、中缀表达式求值算法、c语言中缀表达式求值、中缀表达式求值 c,以便于您获取更多的相关知识。
时间: 2024-08-29 08:16:43