資源簡介
問題描述
中綴表達式就是我們通常所書寫的數學表達式,后綴表達式也稱為逆波蘭表達式,在編譯程序對我們書寫的程序中的表達式進行語法檢查時,往往就可以通過逆波蘭表達式進行。我們所要設計并實現的程序就是將中綴表示的算術表達式轉換成后綴表示,例如,將中綴表達式
(A 一 (B*C 十 D)*E) / (F 十 G )
轉換為后綴表示為:
ABC*D十E*—FG十/
注意:為了簡化編程實現,假定變量名均為單個字母,運算符只有+,-,*,/ 和^(指數運算),可以處理圓括號(),并假定輸入的算術表達式正確。
要求:使用棧數據結構實現 ,輸入的中綴表達式以#號結束
輸入
整數N。表示下面有N個中綴表達式
N個由單個字母和運算符構成的表達式
輸出
N個后綴表達式。
代碼片段和文件信息
#include
#include?
#include?
#define?Error(?Str?)????????FatalError(?Str?)
#define?FatalError(?Str?)???fprintf(?stderr?“%s\n“?Str?)?exit(?1?)
/*?START:?fig3_39.txt?*/
????????#ifndef?_Stack_h
????????#define?_Stack_h
typedef?int?ElementType;
struct?Node;
????????typedef?struct?Node?*PtrToNode;
????????typedef?PtrToNode?Stack;
????????int?IsEmpty(?Stack?S?);
????????Stack?CreateStack(?int?MaxElements?);
????????void?DisposeStack(?Stack?S?);
????????void?MakeEmpty(?Stack?S?);
????????void?Push(?ElementType?X?Stack?S?);
????????ElementType?Top(?Stack?S?);
????????void?Pop(?Stack?S?);
????????#endif??/*?_Stack_h?*/
/*?END?*/
????????struct?Node
????????{
????????????ElementType?Element;
????????????PtrToNode???Next;
????????};
????????int
????????IsEmpty(?Stack?S?)
????????{
????????????return?S->Next?==?NULL;
????????}
????????Stack
????????CreateStack(?int?MaxElements?)
????????{
????????????Stack?S;
S?=?(Stack)malloc(sizeof(struct?Node));
????????????if(?S?==?NULL?)
????????????????FatalError(?“Out?of?space!!!“?);
????????????S->Next?=?NULL;
????????????return?S;
????????}
????????void
????????MakeEmpty(?Stack?S?)
????????{
????????????if(?S?==?NULL?)
????????????????Error(?“Must?use?CreateStack?first“?);
????????????else
????????????????while(?!IsEmpty(?S?)?)
????????????????????Pop(?S?);
????????}
????????void
????????DisposeStack(?Stack?S?)
????????{
????????????MakeEmpty(?S?);
????????????free(?S?);
????????}
????????void
????????Push(?ElementType?X?Stack?S?)
????????{
????????????PtrToNode?TmpCell;
????????????TmpCell?=?(PtrToNode)malloc(?sizeof(?struct?Node?)?);
????????????if(?TmpCell?==?NULL?)
????????????????FatalError(?“Out?of?space!!!“?);
????????????else
????????????{
????????????????TmpCell->Element?=?X;
????????????????TmpCell->Next?=?S->Next;
????????????????S->Next?=?TmpCell;
????????????}
????????}
????????ElementType
????????Top(?Stack?S?)
????????{
????????????if(?!IsEmpty(?S?)?)
????????????????return?S->Next->Element;
????????????Error(?“Empty?stack“?);
????????????return?0;??/*?Return?value?used?to?avoid?warning?*/
????????}
????????void
????????Pop(?Stack?S?)
????????{
????????????PtrToNode?FirstCell;
????????????if(?IsEmpty(?S?)?)
????????????????Error(?“Empty?stack“?);
????????????else
????????????{
????????????????FirstCell?=?S->Next;
????????????
- 上一篇:flow3d二次開發
- 下一篇:面向對象建模技術課程設計
評論
共有 條評論