行编辑程序

#include<iostream.h>
#include<stdio.h>

#include<stdlib.h>     //exit的原型定义
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef int Status;
typedef char SElemType;
typedef struct
{
    SElemType *base;       //栈底指针
    SElemType *top;        //栈顶指针
    int stacksize;       // 当前已分配的栈空间
}SqStack;

void InitStack(SqStack &S)
{
    //构造一个空的顺序栈 S
    S.base=new SElemType[STACK_INIT_SIZE];
    if(!S.base)
        exit(OVERFLOW);
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
}

Status StackEmpty(SqStack S)
{
    //判栈空
    if(S.top==S.base)
        return OK;       //空则返回1
    else
        return ERROR;       //不空返回0
}

Status StackFull(SqStack S)
{
    //判栈满
    if(S.top-S.base>=S.stacksize)
        return OK;            //判栈满,满则返回1
    else
        return ERROR;           //否则返回0
}

Status push(SqStack &S,SElemType x)
{
    //插入元素x为新的栈顶元素
    if(StackFull(S))
        return ERROR;
    *S.top++=x;
    return OK;
}

Status pop(SqStack &S,SElemType &e)
{
    //若栈空返回0,否则栈顶元素退出到e并返回1
    if(StackEmpty(S))
        return ERROR;
    --(S.top);
    e=*(S.top);
    return OK;
}

void StackTravers(SqStack S)
{
    SqStack p=S;
    while(p.top>S.base)
        cout<<*--p.top<<"  ";
    cout<<endl;
}

void GetTop(SqStack S,SElemType &e)
{
    if(StackEmpty(S))
        cout<<"stack is empty!\n";
    e=*--S.top;
}

void ClearStack(SqStack &S)
{
    while(S.top!=S.base)
        --(S.top);
}

void DestroyStack(SqStack &S)
{
    delete[]S.base;
}

void LineEdit()
{
    SqStack S;
    SElemType ch;
    InitStack(S);
    printf("input ch=");
    ch=getchar();
    while(ch!='0')
    {
        //EOF为全文结束符  while1
        while(ch!='\n')
        {
            //while2 line
            switch(ch)
            {
            case'#':pop(S,ch);
                break;
            case'@':ClearStack(S);
                break;    //重置S为空栈
            default:push(S,ch);
                break;
            }//switch
            ch=getchar();      //从终端接收下一个字符
        }//while2 line
        StackTravers(S);
        ClearStack(S);        //重置S为空栈
        if(ch!='0')
        {
            printf("input ch=");
            ch=getchar();
        }
    }//while1
    DestroyStack(S);
}

void main()
{
    LineEdit();
}

 

posted on 2013-04-23 22:10  绕指柔yy  阅读(126)  评论(0编辑  收藏  举报

导航