《数据结构》严蔚敏 用栈实现行编辑程序

参考文章:https://blog.csdn.net/Vit_rose/article/details/52781086

核心代码:void LineEdit(SqStack L)

//order stack
//接受用户输入在缓冲区中,用户发现输入错误的时候,可以补一个退格符"#",“@”退行符
//input: whli# #ilr#e(s# *s)
//         outcha@putchar(* s= # ++);
//output: while(*s)
//          putchar(*s++)


#include<stdio.h>
#include<stdlib.h>

#define STACK_INIT_SIZE 100
#define STACKINCREMENT  10

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0


typedef char SElemType;
typedef int Status;

typedef struct
{
	SElemType *base;
	SElemType *top;

	int stackesize;

}SqStack;

Status
InitStack(SqStack *S)
{
	(*S).base =(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SqStack));
	if(!S->base)
		exit(ERROR);

	(*S).top = (*S).base; // If you don't understand it ,I think you should learn about the structure in C firstly.
	(*S).stackesize = STACK_INIT_SIZE;

	return OK;
}

// Well,Remeber,It's only use in allocation stack dynamic



Status ClearStack(SqStack *S)
{
	//(*S).top = (*S).base;

	while(S->base != S->top)
		S->top -- ;
	S->stackesize = 0;

	return OK;
}

Status StackEmpty(SqStack *S)
{
	if(S->top == S->base)
		return TRUE;
	else
		return FALSE;

	// or use ? : make things seems concise

}
// When Push,first add then change the point

Status
Push(SqStack *S,SElemType e)
{
	//lack of verfy
	if(S->top - S->base >= S->stackesize)
	{
		S->base = (SElemType*)realloc(S->base,
			(S->stackesize + STACK_INIT_SIZE)*sizeof(SElemType));
		if(!S->base)
			exit(ERROR);
		S->top = S->base + S->stackesize;
		S->stackesize += STACKINCREMENT;
	}
	

	////////// the first ////
	*(*S).top = e;
	S->top ++;
	
	return OK;	

}

Status
Pop(SqStack *S)
{
	if(StackEmpty(S) == 0)
	{
		S->top --;
		return OK;
	}
	else
		return ERROR;

}

Status
DestoryStack(SqStack *S)
{
	if(S->stackesize > 0)
	{
		S->stackesize = 0;
	}

	free(S);
	S = NULL;
	return OK;

}


void
LineEdit(SqStack L)
{
    char c,ch,*p;
    printf("输入:");
    ch = getchar();  //从终端接收第一个字符
    while(ch != EOF){
        printf("输出:");
        while(ch != EOF && ch != '\n'){
            switch(ch)
            {
                case '#':
                    Pop(&L);
                    break;
                case '@':
                    ClearStack(&L);
                    break;
                default :
                    Push(&L,ch);
                    break;
            }//switch
            ch = getchar();  //从终端接收下一个字符
        }//while
    p = L.base;      // 我就死在这一步上 是char *类型
    while(p != L.top){
        printf("%c",*p);
        ++p;
    }
    printf("\n");
    ClearStack(&L);
    if(ch != EOF)
        printf("输入:");
        ch = getchar();
    }
}



int main(int argc, char const *argv[])
{
	SqStack L;
	InitStack(&L);

	LineEdit(L);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37414405/article/details/85931456
今日推荐