题目描述
输入
输出
示例输入
whli##ilr#e(s#*s) outcha@putchar(*s=#++);
示例输出
while(*s)putchar(*s++);
#include <stdio.h> #include <stdlib.h> #include<malloc.h> #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 #define OK 1 #define OVERFLOW -1 #define ERROR -2 typedef char SElemType; typedef struct { SElemType *base;//栈底指针 SElemType *top;//栈顶指针 int stacksize;//当前已分配的存储空间,以元素为单位 }SqStack;
void InitStack(SqStack &S)// 构造一个空栈S { S.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType)); if(!S.base) exit(OVERFLOW);//存储分配失败 S.top=S.base; S.stacksize=STACK_INIT_SIZE; } void DestroyStack(SqStack &S)//销毁栈; { S.top=NULL; S.stacksize=0; } void ClearStack(SqStack &S)//清空栈; { S.top=S.base; }
void Push(SqStack &S,SElemType e)// 插入元素e为新的栈顶元素 { if(S.top-S.base>=S.stacksize) {// 当前存储空间已满,增加分配 S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType)); if(!S.base) exit(OVERFLOW);//存储分配失败 S.top=S.base+S.stacksize; S.stacksize+=STACKINCREMENT;//增加存储容量 } *S.top++=e; }
int Pop(SqStack &S,SElemType &e)//若栈不空,则删除S的栈顶元素,并 //用e返回其值,并返回OK,否则返回 //ERROR { if(S.top==S.base) return ERROR; e=*--S.top; return OK; }
int GetTop(SqStack S,SElemType &e)//若栈不空,则用e返回S的栈顶元素,并 //返回OK,否则返回ERROR { if(S.top==S.base) return ERROR; e=*(S.top-1); return OK; }
void PutStack(SqStack &S) { while(S.top>S.base) { S.top--; printf("%d",*S.top); } printf("\n"); }
void LineEdit()//行编译函数; { char ch,*temp; SqStack S;//栈的定义; InitStack(S);//栈的初始化; ch=getchar(); while(ch!=EOF) { while(ch!=EOF&&ch!='\n') { switch(ch) { case '#':Pop(S,ch);break;//出栈操作; case '@':ClearStack(S);break;//清空栈; default :Push(S,ch);break;//进栈; } ch=getchar(); } temp=S.base;//temp指针指向base指针; while(temp!=S.top) { printf("%c",*temp); ++temp; } ClearStack(S);//清空栈; printf("\n"); if(ch!=EOF) { ch=getchar(); } } DestroyStack(S);//销毁栈; }
int main() { LineEdit(); return 0; }
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> using namespace std; #define maxsize 10000 typedef struct Stack { int Size; char *top,*base; } Stack; bool Empty(Stack &s) { if (s.top == s.base) { return 1; } return 0; } void Creat(Stack &s)//栈的初始化; { s.base=new char[maxsize]; s.top=s.base; s.top++; s.base++; s.Size=maxsize; } void push(Stack &s,char e) { if (s.top-s.base >= s.Size) { s.base=(char *)realloc(s.base,2*maxsize*sizeof(Stack)); s.Size+=maxsize; ///s.top=s.base+s.Size; } s.top++; *s.top=e; } void pop(Stack &s) { if (s.top != s.base) { s.top--; } } void print(Stack &s) { while (!Empty(s)) { cout<<*s.top; pop(s); } } void out(Stack &s)//栈内元素的输出 { s.base++; while(s.base<=s.top) { cout<<*s.base; s.base++; } cout<<endl; } void Clear(Stack &s) { while (!Empty(s)) { pop(s); } } void edit(Stack &s,char str[]) { int i; for(i=0; str[i]; i++) { if (str[i] == '#' && !Empty(s)) { pop(s);//出栈; } else if(str[i] == '@') { Clear(s);//清空栈; } else if (str[i]!='#'&&str[i]!='@') { push(s,str[i]);//进栈; } } } int main() { char str[333]; while(gets(str)!=NULL) { Stack s; Creat(s); edit(s,str); out(s); } return 0; }