设立一个缓冲区,用以接受用户输入的一行字符,然后逐行存入用户数据区,允许用户输入出差错,并在发现有误的时候可以加以改正。
“#”是退格符,表示前一个字符无效;“@”是退行符,表示当前行中的字符均无效。
"main.c"
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
/*
'#'为退格符,'@'为退行符
*/
void LineEditor();
void printStack(Stack* s);
void clearStack(Stack* s);
int main() {
LineEditor();
return 0;
}
void LineEditor() {
printf("Welcome to Line Editor\n");
printf("'#' to delete a letter, '@' to delete the whole line!\n");
printf("Let's begin:\n");
Stack s;
InitStack(&s);
char ch = getchar();
if((ch == '#' || ch == '@') && isEmpty(&s)) { printf("nothing to delete!"); exit(1); }
push(&s, ch);
while(ch != EOF) {
while(ch != EOF && ch != '\n') {
switch (ch)
{
case '#':
pop(&s);
break;
case '@':
clearStack(&s);
break;
default:
push(&s, ch);
break;
}
ch = getchar();
}
printStack(&s);
printf("\n");
if(ch != EOF) {
ch = getchar();
if((ch == '#' || ch == '@') && isEmpty(&s)) { printf("nothing to delete!"); exit(1); }
}
}
}
void printStack(Stack* s) {
//利用递归实现栈内元素逆序打印
if(isEmpty(s)) { return; }
else {
ElementType i = pop(s);
printStack(s);
printf("%c", i);
}
}
void clearStack(Stack* s) {
while(!isEmpty(s)) { pop(s); }
}
"stack.h"
#ifndef STACK_H
#define STACK_H
#define ElementType char
//结构体的声明以及定义
typedef struct node {
ElementType data;
struct node* next;
} Node;
typedef struct stack {
Node* top;
int size;
} Stack;
//各种函数的声明
void InitStack(Stack* s);
void push(Stack* s, ElementType data);
ElementType pop(Stack* s);
ElementType peek(Stack* s);
_Bool isEmpty(Stack* s);
#endif
"stack.c"
#include <stdlib.h>
#include <stdbool.h>
#include "stack.h"
void push(Stack* s, ElementType data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = s->top;
s->top = node;
s->size++;
}
ElementType pop(Stack* s) {
if (isEmpty(s)) {
return -1; // 栈为空,返回 -1 表示出错
}
Node* node = s->top;
ElementType data = node->data;
s->top = node->next;
s->size--;
free(node);
return data;
}
ElementType peek(Stack* s) {
if (isEmpty(s)) {
return -1; // 栈为空,返回 -1 表示出错
}
return s->top->data;
}
_Bool isEmpty(Stack* s) {
return s->size == 0;
}
void InitStack(Stack* s) {
s->size = 0;
s->top = NULL;
}