通过栈将中缀表达式转换为后缀表达式并根据后缀表达式求解,包含的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);
- }