二 课程设计2——算术表达式求值
一、需求分析
二、程序的主要功能 三、程序运行平台 四、数据结构
五、算法及时间复杂度 六、测试用例 七、程序源代码
三 感想体会与总结
算术表达式求值
一、需求分析
一个算术表达式是由操作数(operand)、运算符(operator)和界限符(delimiter)组成的。假设操作数是正整数,运算符只含加减乘除等四种运算符,界限符有左右括号和表达式起始、结束符“#”,如:#(7+15)*(23-28/4)#。引入表达式起始、结束符是为了方便。编程利用“算符优先法”求算术表达式的值。 二、程序的主要功能
(1) 从键盘读入一个合法的算术表达式,输出正确的结果。 (2) 显示输入序列和栈的变化过程。
三、程序运行平台
Visual C++ 6.0版本
四、数据结构
本程序的数据结构为栈。 (1)运算符栈部分:
struct SqStack //定义栈 {
char *base; //栈底指针 char *top; //栈顶指针 int stacksize; //栈的长度 };
.
int InitStack (SqStack &s) //建立一个空栈S {
if (!(s.base = (char *)malloc(50 * sizeof(char)))) exit(0);
s.top=s.base; s.stacksize=50; return OK; }
char GetTop(SqStack s,char &e) //运算符取栈顶元素 {
if (s.top==s.base) //栈为空的时候返回ERROR {
printf(\运算符栈为空!\\n\ return ERROR; }
else
e=*(s.top-1); //栈不为空的时候用e做返回值,返回S的栈顶元素,并返回OK return OK; }
int Push(SqStack &s,char e) //运算符入栈 {
if (s.top-s.base >= s.stacksize) { printf(\运算符栈满!\\n\ s.base=(char*)realloc (s.base,(s.stacksize+5)*sizeof(char) ); //栈满的时候,追加5个存储空间
if(!s.base) exit (OVERFLOW); s.top=s.base+s.stacksize; s.stacksize+=5; }
*(s.top)++=e; //把e入栈 return OK; }
int Pop(SqStack &s,char &e) //运算符出栈 {
if (s.top==s.base) //栈为空栈的时候,返回ERROR {
printf(\运算符栈为空!\\n\ return ERROR; }
else {
.
.
e=*--s.top; //栈不为空的时候用e做返回值,删除S的栈顶元素,并返回OK return OK; } }
int StackTraverse(SqStack &s) //运算符栈的遍历 {
char *t; t=s.base ;
if (s.top==s.base) {
printf(\运算符栈为空!\\n\ //栈为空栈的时候返回ERROR return ERROR; }
while(t!=s.top) { printf(\栈不为空的时候依次取出栈内元素 t++; }
return ERROR; }
(2)数字栈部分:
struct SqStackn //定义数栈 {
int *base; //栈底指针 int *top; //栈顶指针
int stacksize; //栈的长度 };
int InitStackn (SqStackn &s) //建立一个空栈S {
s.base=(int*)malloc(50*sizeof(int));
if(!s.base)exit(OVERFLOW); //存储分配失败 s.top=s.base; s.stacksize=50; return OK; }
int GetTopn(SqStackn s,int &e) //数栈取栈顶元素 {
if (s.top==s.base) {
printf(\运算数栈为空!\\n\栈为空的时候返回ERROR return ERROR; }
.
.
else
e=*(s.top-1); //栈不为空的时候,用e作返回值,返回S的栈顶元素,并返回OK return OK; }
int Pushn(SqStackn &s,int e) //数栈入栈 {
if (s.top-s.base >=s.stacksize) { printf(\运算数栈满!\\n\栈满的时候,追加5个存储空间 s.base=(int*)realloc (s.base,(s.stacksize+5)*sizeof(int) ); if(!s.base) exit (OVERFLOW); s.top=s.base+s.stacksize; //插入元素e为新的栈顶元素 s.stacksize+=5; }
*(s.top)++=e; //栈顶指针变化 return OK; }
int Popn(SqStackn &s,int &e) //数栈出栈 {
if (s.top==s.base) {
printf(\运算符栈为空!\\n\栈为空栈的视时候,返回ERROR
return ERROR; }
else { e=*--s.top; //栈不空的时候,则删除S的栈顶元素,用e返回其值,并返回OK
return OK; } }
int StackTraversen(SqStackn &s) //数栈遍历 {
int *t;
t=s.base ;
if (s.top==s.base) {
printf(\运算数栈为空!\\n\栈为空栈的时候返回ERROR return ERROR; }
while(t!=s.top) {
.
相关推荐: