栈的应用:表达式求值的设计
Stack Whereat; char sample;
InputFile = fopen(\ /*打开文件*/ OutputFile = fopen(\
Whereat = malloc(sizeof(struct Node)); /*给 Whereat分配空间*/ Whereat->Next = NULL;
if (!InputFile || !OutputFile) { /*错误处理*/ printf(\ return(1); }
sample = getc(InputFile); while ( sample != EOF){ Temp = fopen(\ /*生成Temp文件*/ ungetc(sample,InputFile); /* put back sample字符*/ ConvertToPost(InputFile,Whereat,Temp); /*中缀变后缀*/ if (PrintError){ /*错误处理*/ fprintf(OutputFile,\ fscanf(InputFile,\ PrintError = 0;
} else if (IsEmpty(Whereat) == 1){ /*跳过在input文件中的空格*/ } else if (IsEmpty(Whereat) != 1){ Reverse(Whereat); if (Top(Whereat) == 'B'){ /*错误处理,*/ /*A表示操作数B表示运算符*/ PrintError = 1; /*后缀表达式第一个元素应是操作数而不是运算符号*/
} fclose(Temp); Temp = fopen(\ Calculate(OutputFile, Whereat,Temp); /*计算结果*/ } fclose(Temp); MakeEmpty(Whereat); /* 清空Whereat用来处理下一行*/ putc('\\n',OutputFile); /* 在输出文件中换行*/ sample = getc(InputFile);
} /* While循环结束*/
11
栈的应用:表达式求值的设计
free(Whereat); fclose(InputFile); fclose(OutputFile);
remove(\ /* 删除Temp.txt*/ return 1; }
/******检查堆栈是否为空******/ int IsEmpty(Stack S) {
return(S->Next==NULL); }
/******检查float堆栈是否为空******/ int FIsEmpty(FStack S) {
return(S->Next==NULL); }
/******弹出栈顶元素******/ void Pop(Stack S) { PtrToNode FirstCell; if (IsEmpty(S)) perror(\ else{ FirstCell = S->Next; S->Next = S->Next->Next; free(FirstCell); }
}
/******弹出float栈顶元素******/ void FPop(FStack S) {
Ptr_Fn FirstCell; if (FIsEmpty(S)) perror(\ else{ FirstCell = S->Next; S->Next = S->Next->Next; free(FirstCell);
12
栈的应用:表达式求值的设计
} }
/******将堆栈置空******/ void MakeEmpty(Stack S) {
if (S == NULL) perror(\ else while (!IsEmpty(S)) Pop(S); }
/******将float堆栈置空******/ void FMakeEmpty(FStack S) {
if (S == NULL) perror(\ else while (!IsEmpty(S)) Pop(S); }
/******元素进栈******/ void Push(char X, Stack S) {
PtrToNode TmpCell;
TmpCell = (PtrToNode)malloc(sizeof(struct Node)); if (TmpCell == NULL) perror(\ else{
TmpCell->Element = X; TmpCell->Next = S->Next; S->Next = TmpCell; } }
/******float元素进栈******/ void FPush(float X, FStack S) {
Ptr_Fn TmpCell;
TmpCell = (Ptr_Fn)malloc(sizeof(struct FNode));
13
栈的应用:表达式求值的设计
if (TmpCell == NULL) perror(\ else{ TmpCell->Element = X; TmpCell->Next = S->Next; S->Next = TmpCell; } }
/******返回栈顶元素******/ char Top(Stack S)
{
if (!IsEmpty(S)) return S->Next->Element; perror(\ exit(1); return 0; }
/******返回float栈顶元素******/ float FTop(FStack S)
{
if (!FIsEmpty(S)) return S->Next->Element; perror(\ exit(1); return 0; }
/******将堆栈元素倒置******/ void Reverse(Stack Rev) { }
Stack Tempstack;
Tempstack = malloc(sizeof(struct Node)); Tempstack->Next = NULL; while (!IsEmpty(Rev)){ Push(Top(Rev),Tempstack); /*将元素压栈到一个临时堆栈*/ Pop(Rev); } Rev->Next = Tempstack->Next; /*指向新的堆栈*/
14