数据结构 栈应用(行编辑程序)

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <math.h>
  4 
  5 #define STACK_INIT_SIZE 10
  6 #define STACKINCREMENT   2
  7 #define    OK      1
  8 #define    FALSE 0
  9 
 10 typedef int SElemType;
 11 typedef int Status;
 12 
 13 FILE *fp;
 14 
 15 typedef struct SqStack
 16 {
 17     SElemType *base;
 18     SElemType *top;
 19     int     stacksize;
 20 }SqStack;
 21 
 22 Status InitStack(SqStack *S)
 23 {
 24     (*S).base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
 25     if(!(*S).base)
 26         exit(OVERFLOW);
 27     (*S).top = (*S).base;
 28     (*S).stacksize = STACK_INIT_SIZE;
 29     return OK;
 30 }
 31 
 32  Status DestroyStack(SqStack *S)
 33  {
 34    free((*S).base);
 35    (*S).base=NULL;
 36    (*S).top=NULL;
 37    (*S).stacksize=0;
 38    return OK;
 39  }
 40 
 41  Status ClearStack(SqStack *S)
 42  {
 43    (*S).top=(*S).base;
 44    return OK;
 45  }
 46 
 47  Status Push(SqStack *S,SElemType e)
 48  { 
 49    if((*S).top-(*S).base>=(*S).stacksize) 
 50    {
 51      (*S).base=(SElemType *)realloc((*S).base,((*S).stacksize+STACKINCREMENT)*sizeof(SElemType));
 52      if(!(*S).base)
 53        exit(OVERFLOW); 
 54      (*S).top=(*S).base+(*S).stacksize;
 55      (*S).stacksize+=STACKINCREMENT;
 56    }
 57    *((*S).top)++=e;
 58    return OK;
 59  }
 60 
 61  Status Pop(SqStack *S,SElemType *e)
 62  {
 63    if((*S).top==(*S).base)
 64      return FALSE;
 65    *e=*--(*S).top;
 66    return OK;
 67  }
 68 
 69 
 70  Status StackTraverse(SqStack S,Status(*visit)(SElemType))
 71  {
 72    while(S.top>S.base)
 73      visit(*S.base++);
 74    printf("\n");
 75    return OK;
 76  }
 77 
 78  Status Copy(SElemType c)
 79  {
 80    fputc(c,fp);
 81    return OK;
 82  }
 83 
 84 
 85 void LineEdit()
 86 {
 87     SqStack S;
 88     SElemType ch,c;
 89     InitStack(&S);
 90     printf("请输入一个文本文件,^Z结束输入:\n");
 91     ch=getchar();
 92     while(ch!=EOF)
 93     {
94 while(ch!=EOF&&ch!='\n') 95 { 96 switch(ch) 97 { 98 case '#':Pop(&S,&c); 99 break;
100 case '@':ClearStack(&S); 101 break;
102 default :Push(&S,ch); 103 } 104 ch=getchar();
105 } 106 StackTraverse(S,Copy); 107 ClearStack(&S); 108 fputc('\n',fp); 109 if(ch!=EOF) 110 ch=getchar(); 111 } 112 DestroyStack(&S); 113 } 114 115 void main() 116 { 117 fp = fopen("ED.txt","w"); 118 if (fp) 119 { 120 LineEdit(); 121 fclose(fp); 122 } 123 else 124 printf("建立文件失败!\n"); 125 126 }

 

posted on 2012-04-28 19:58  QLinux  阅读(1392)  评论(0编辑  收藏  举报

导航