Through the stack to convert infix expression to suffix expression and based on the suffix expression solution, including Header.h for the previous stack operation related function instance program, changed to header file on the line. Practice + record, Master ignore.
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 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!= ' ") {if (Isalnum (*lpcontainer)) {sprintf (lptemp,"%c ", *LPC
Ontainer);
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!= ' ") {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) +p
OP (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); }
This article is from the "About:blank h4cking" blog, please be sure to keep this source http://pnig0s1992.blog.51cto.com/393390/812563