|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- #define Stack_max_size 20
- typedef char ElemType;
- //定义栈的基础结构体
- typedef struct
- {
- ElemType *base;//栈底指针
- ElemType *top;//栈顶指针
- int Stack_size;//栈的长度
- }Sqstack;//栈的别名
- //栈的初始化
- void Init_stack(Sqstack *s)
- {
- s->base = (ElemType*)malloc(Stack_max_size * sizeof(ElemType));
- if(!s->base)
- {
- printf("申请内存失败!\n");
- exit(0);
- }
- s->top == s->base;
- s->Stack_size = Stack_max_size;
- }
- //栈的压入操作
- void Push(Sqstack *s, ElemType c)
- {
- if(s->top - s->base >= s->Stack_size)
- {
- printf("该栈已满!\n");
- exit(0);
- }
- *(s->top) = c;
- s->top++;
- }
- //栈的弹出操作
- int Pop(Sqstack *s, ElemType *c)
- {
- if(s->base == s->top)
- {
- printf("该栈已空!\n");
- exit(0);
- }
- s->top--;
- *c = *(s->top);
-
- return 0;
- }
- //栈长度测量函数
- int StackLen(Sqstack s)
- {
- return (s.top - s.base);
- }
- int main()
- {
- Sqstack s;//创建一个栈的变量
- Init_stack(&s);//初始化栈
- char c;//用于接收输入的数字和运算符
- char e;
- printf("请输入需要转换的表达式, 输入#为结束:\n");
- scanf("%c", &c);
- while(c != '#')
- {
- if(c>='0' && c<='9')
- {
- printf("%c", c);
- }
- else if(')' == c)
- {
- Pop(&s, &e);
- while('(' != e)
- {
- printf("%c", e);
- Pop(&s, &e);
- }
- }
- else if('+' == c || '-' == c)
- {
-
- if(!StackLen(s))
- {
- Push(&s, c);
- }
- else
- {
- do
- {
- Pop(&s, &e);//拿出栈顶元素进行比较
- if('(' == e)
- {
- Push(&s, e);
- }
- else
- {
- printf("%c", e);
- }
- }while(s.top == s.base || '(' == e);
- Push(&s, c);//对比结束后将新接收的字符压入栈中
- }
- }
- else if('*'==c || '/'==c || ')'==c)
- {
- Push(&s, c);
- }
- else
- {
- printf("出错,请检查用户输入!\n");
- }
- scanf("%c", &c);
- }
- while(s.top - s.base != 0)//结束后,将栈中剩余元素打印出来
- {
- Pop(&s, &e);
- printf("%c", e);
- }
- return 0;
- }
复制代码
除了下面的等号,运行正常,至于逻辑上有没有错误,不知道。还有一点就是 由程序员自行分配的内存空间应该叫堆。
|
|