表达式编辑

来源:互联网 发布:java发送get post请求 编辑:程序博客网 时间:2024/05/29 02:59

使用栈模拟简单的表达式编辑。


#include <stdlib.h>#include <stdio.h>#define MAXSIZE 100typedef char Datatype;typedef struct{int top;Datatype data[MAXSIZE];}seqstack,*pseqstack;pseqstack init_stack(void){pseqstack s;s = (pseqstack)malloc(sizeof(seqstack));if (s)s->top = -1;elseprintf("申请失败");return s;}int empty_stack(pseqstack s){if (!s){printf("栈不存在");return(-1);}if (s->top == -1)return(1);elsereturn(0);}int push_stack(pseqstack s, Datatype dat){if (!s){printf("栈不存在,无法入栈");return(-1);}if (s->top == MAXSIZE - 1){printf("栈满,无法插入");return(0);}s->top++;s->data[s->top] = dat;return(1);}int pop_stack(pseqstack s, Datatype *dat){if (!s){printf("栈不存在,无法出栈");return(-1);}if (empty_stack(s)){printf("栈空,无法出栈");return(0);}else{*dat = s->data[s->top];s->top--;return(1);}}int get_top(pseqstack s, Datatype *t){if (!s){printf("栈不存在");return(-1);}if (empty_stack(s)){printf("栈空,无法出栈");return(0);}else{*t = s->data[s->top];return(1);}}int clear_stack(pseqstack s){if (!s){printf("栈不存在");return(-1);}s->top = -1;}void destroy_stack(pseqstack *s){if (*s)free(*s);*s = NULL;}void display_stack(pseqstack s){if (! s){printf("栈不存在");}else{for (int i = -1; i < s->top; i++)printf("%d\n", s->data[i + 1]);}}int line_edit(){pseqstack line = init_stack();char ch,temp;ch = getchar();while (ch != EOF){while (ch != EOF && ch != '\n')//因为后面的getchar引入了新变量,不一定满足宽泛的条件,要从严限制{switch (ch){case '#':pop_stack(line, &temp); break;case '@':clear_stack(line); break;default:push_stack(line, ch); break;}ch = getchar();}display_stack(line);//接收到EOF或回车,则对已接收的字符串进行处理clear_stack(line);if (ch != EOF)//若接收到的是回车,则继续读取下一个字符串ch = getchar();}destroy_stack(&line);return(1);}int main(){int r=line_edit();while (true){}}


0 0
原创粉丝点击