C语言数据结构——栈、行编辑程序

xiaoxiao2021-02-28  67

/*顺序栈头文件:SeqStack.h*/ #include <stdio.h> #include <stdlib.h> #define STACKSIZE 100 typedef char DataType; typedef struct { DataType stack[STACKSIZE]; int top; }SeqStack; void InitStack(SeqStack *S);//初始化栈 int StackEmpty(SeqStack S);//判断栈是否为空 int GetTop(SeqStack S, DataType *e);//取栈顶元素 int PushStack(SeqStack *S, DataType e);//入栈 int PopStack(SeqStack *S, DataType *e);//出栈 int StackLength(SeqStack S);//求栈长度 void ClearStack(SeqStack *S);//清空栈 void InitStack(SeqStack *S)//将栈S初始化为空栈 { S->top = 0; } int StackEmpty(SeqStack S)//判断栈是否为空,栈为空返回1,否则返回0 { if (S.top == 0) { return 1; } else { return 0; } } int GetTop(SeqStack S, DataType *e) //取栈顶元素,将栈顶元素值返回给e,并返回1表示成功,返回0表示失败 { if (S.top <= 0) { printf("栈已经空!n"); return 0; } else { *e = S.stack[S.top - 1];//取栈顶元素 return 1; } } int PushStack(SeqStack *S,DataType e)//进栈操作 //将元素e进栈,元素进栈成功返回1,否则返回0 { if(S->top >= STACKSIZE-1) //元素进栈前,判断是否栈已满 { printf("栈已满,不能入栈!"); return 0; } else { S->stack[S->top] = e; //元素e进栈 S->top++; //修改栈顶指针 return 1; } } int PopStack(SeqStack *S,DataType *e)//出栈操作 { if(S->top <= 0) { printf("栈已经没有元素,不能出栈!n"); return 0; } else { S->top--; //先修改栈顶指针,即出栈 *e = S->stack[S->top]; //将出栈元素赋值给e return 1; } } int StackLength(SeqStack S)//返回栈长度 { return S.top; } void ClearStack(SeqStack *S)//清空栈 { S->top = 0; //将栈顶指针置0 } typedef char DataType; void LineEdit(); int main() { LineEdit(); } void LineEdit() // 行编辑程序 { SeqStack S; char ch; DataType e; DataType a[50]; int i, j = 0; InitStack(&S); printf("请输入字符序列(#表示前一个字符无效,@表示当前行无效).\n"); ch = getchar(); while (ch != '\n') { switch (ch) { case '#': //出现‘#’,而且栈不空,将栈顶元素出栈 if (!StackEmpty(S)) PopStack(&S, &ch); break; case '@': //出现‘@’,将栈清空 ClearStack(&S); break; default: PushStack(&S, ch); } ch = getchar(); //读入下一个字符 } while (!StackEmpty(S)) { PopStack(&S, &e); //将字符出栈,并存入数组a中 a[j++] = e; } /*栈后进先出,直接出栈字符序列相反,所以用数组倒序输出*/ for (i = j - 1; i >= 0; i--) //输出正确的字符序列 printf("%c", a[i]); printf("\n"); ClearStack(&S); }
转载请注明原文地址: https://www.6miu.com/read-61534.html

最新回复(0)