如果遇到‘#’,表示后退一格,即前一字符无效,如果遇到@,表示前一单词无效,即退出到空格或所在行头为止。采用栈实现。 输入:whli##ilr#e(s#*s++) 输入包含若干行,由各种字符构成。 输出:while(*s++) 利用描述规则输出最后的文本内容。
Seqstack.h
#ifndef _SEQSTACK_H_ #define _SEQSTACK_H_ #include<iostream> #include<assert.h> using namespace std; typedef char ElemType; #define STACK_MAX_SIZE 20 typedef struct Stack { ElemType *base; int top; int capacity; }Stack; void InitStack(Stack *stack); bool isfull(Stack *stack); bool isempty(Stack *stack); bool push(Stack *stack,ElemType x); ElemType pop(Stack *stack,ElemType *x); bool show_stack(Stack *stack); ElemType GetTop(Stack *stack,ElemType *x); void clear(Stack *stack); void destroy(Stack *stack); #endif //_SEQSTACK_H_
Seqstack.cpp
#include"Seqstack.h" void InitStack(Stack *stack) { stack->base = (ElemType *)malloc(sizeof(ElemType)*STACK_MAX_SIZE); //stack->base = (ElemType *)malloc(sizeof(ElemType)); assert(stack->base != NULL); stack->top = 0; stack->capacity = STACK_MAX_SIZE; } bool isfull(Stack *stack) { return stack->top == stack->capacity; } bool isempty(Stack *stack) { return stack->top == 0; } bool push(Stack *stack,ElemType x) { if(isfull(stack)) return false; stack->base[stack->top++] = x; return true; } ElemType GetTop(Stack *stack,ElemType *x) { if(isempty(stack)) { cout<<"栈空!"<<endl; } return stack->base[stack->top-1]; } bool show_stack(Stack *stack) { if(isempty(stack)) return false; for(int i = stack->top-1;i>=0;--i) cout<<stack->base[i]<<endl; return true; } void clear(Stack *stack) { stack->top = 0; } void destroy(Stack *stack) { clear(stack); free(stack->base); stack->capacity = 0; } ElemType pop(Stack *stack,ElemType *e) { if(isempty(stack)) return false; *e = stack->base[--stack->top]; return true; }main.cpp<pre name="code" class="cpp">#include"Seqstack.h" void LineEdit() { Stack st; Stack st2; int ch; char e; InitStack(&st); InitStack(&st2); cout<<"please input:"; ch = getchar(); while(ch != EOF) { while(ch!=EOF && ch!='\n') { switch(ch) { case '#': if(!isempty(&st)) pop(&st,&e); break; case '@': clear(&st); break; default : if(!isfull(&st)) push(&st,ch); break; } ch = getchar(); } while(st.top>0) { pop(&st, &e); push(&st2, e); } cout<<"now:"; while(st2.top>0) { pop(&st2,&e); cout<<e; } cout<<endl; clear(&st); clear(&st2); cout<<"please input:"; if(ch!=EOF) ch = getchar(); } destroy(&st); destroy(&st2); } int main(void) { LineEdit(); return 0; }输出:
原文地址:http://blog.csdn.net/chenmengmengx/article/details/45629443