头文件
stackh.h
#ifndef STACKH_H_INCLUDED
#define STACKH_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 10
#define STACK_INCR_SIZE 3
typedef char ElemType ;
typedef struct
{
ElemType* sbase ;
ElemType* stop ;
int stacksize ;
} STACK ;
int InitStack( STACK* s ) ;
int DestroyStack( STACK* s ) ;
int IsEmpty( STACK* s ) ;
int ClearStack(STACK* s ) ;
int GetTop( STACK* s , ElemType* e ) ;
int GetLength( STACK* s ) ;
int Push( STACK* s , ElemType e ) ;
int Pop( STACK* s , ElemType* e ) ;
int TraverseStack( STACK* s ) ;
int StackToFile( STACK* s ) ;//write stack to file
//application
int LineEditor() ;
#endif // STACKH_H_INCLUDED
//实现栈
#include "stackh.h"
int InitStack( STACK* s )
{
s->sbase = ( ElemType* )malloc( STACK_INIT_SIZE * sizeof( ElemType ) ) ;
if( !s->sbase )
{
printf( "OVERFLOW!\n") ;
exit( 1 ) ;
}
s->stop = s->sbase ;
s->stacksize = STACK_INIT_SIZE ;
return 0 ;
}
int DestroyStack( STACK* s )
{
free( s->sbase ) ;
s->sbase = NULL ;
s->stop = NULL ;
s->stacksize = 0 ;
return 0 ;
}
int ClearStack( STACK* s )
{
s->stop = s->sbase ;
return 0 ;
}
int IsEmpty( STACK* s )
{
if( s->sbase == s->stop )
{
return 1 ;
}
else
{
return 0 ;
}
}
int GetTop( STACK* s , ElemType* e )
{
if( s->sbase == s->stop )
{
printf( "OVERFLOW!\n" ) ;
exit( 1 ) ;
}
e = s->stop - 1 ;//?
return 0 ;
}
int GetLength( STACK* s )
{
return s->stop - s->sbase ;
}
int Push( STACK* s , ElemType e )
{
if( GetLength( s ) >= s->stacksize )
{
s->sbase = ( ElemType* )realloc( s->sbase , (s->stacksize +
STACK_INCR_SIZE) * sizeof( ElemType ) ) ;
if( !s->sbase )
{
printf( "OVERFLOW!\n" ) ;
}
s->stop = s->sbase + s->stacksize ;
s->stacksize += STACK_INCR_SIZE ;
}
*s->stop++ = e ;
return 0 ;
}
int Pop( STACK* s , ElemType* e )
{
if( IsEmpty( s ) )
{
printf( "OVERFLOW!\n" ) ;
exit( 1 ) ;
}
*e = *--s->stop ;
return 0 ;
}
int TraverseStack( STACK* s )
{
if( s->sbase == s->stop )
{
printf( "OVERFLOW!\n" ) ;
exit( 1 ) ;
}
ElemType* p = s->sbase ;
while( p != s->stop )
{
printf( "%c\t" , *p++ ) ;
}
printf( "\n" ) ;
return 0 ;
}
int StackToFile( STACK* s )
{
FILE* fp = fopen( "f://codeblocks//stacktofile.txt" , "a+" ) ;
fwrite( s->sbase , sizeof( ElemType ) , GetLength( s ) , fp ) ;
fclose( fp ) ;
return 0 ;
}
//实现行编辑器
#include "stackh.h"
int LineEditor()
{
char ch ;
STACK sline ;
InitStack( &sline ) ;
while( ( ch = getchar( ) ) != EOF )
{
switch( ch )
{
case '#' :
if( IsEmpty( &sline ) )
{
printf( "ERROR!\n" ) ;
}
char tm ;
Pop( &sline , &tm ) ;
if( tm == '\\' )
{
Push( &sline , ch ) ;
}
break ;
case '@' :
if( IsEmpty( &sline ) )
{
printf( "ERROR!\n" ) ;
}
char tmp ;
Pop( &sline , &tmp ) ;
if( tmp == '\\' )
{
Push( &sline , ch ) ;
}
else
{
ClearStack( &sline ) ;
}
break ;
case '\n' :
Push( &sline , ch ) ;
TraverseStack( &sline ) ;
StackToFile( &sline ) ;
ClearStack( &sline ) ;
break ;
default :
Push( &sline , ch ) ;
break ;
}
}
return 0 ;
}
//main函数
#include "stackh.h"
int main()
{
LineEditor() ;
return 0;
}