行编辑程序(栈和队列)
时间: 1ms 内存:128M
描述:
一个简单的行编辑程序的功能是:接受用户从终端输入的程序或数据,并存入用户的数据区。答应用户输入出错时可以及时更正。可以约定#为退格符,以表示前一个字符无效,@为退行符,表示当前行所有字符均无效。
输出更正后的程序。
输入:
whli##ilr#e(s#*s)
输出:
while(*s)
示例输入:
outcha@putchar(*s=#++)
示例输出:
putchar(*s++)
提示:
参考答案(内存最优[752]):
#include <stdio.h>
#include <stdlib.h>
#define STACK_INT_SIZE 100
typedef struct stu{
int *base;
int *top;
int stacksize;
}stack;
void initstack(stack *s){
s->base=s->top=(int *)malloc(STACK_INT_SIZE*sizeof(int));
s->stacksize=STACK_INT_SIZE;
}
void push(stack *s,char e){
*s->top++=e;
}
int pop(stack *s,char *e){
if(s->base==s->top)
return 0;
s->top--;
*e=*(s->top);
return 1;
}
void clear(stack *s)
{
s->base=s->top;
s->stacksize=0;
}
char gettop(stack *s)
{
return *(s->top-1);
}
void main()
{
stack s,s1;
char ch;
int i;
initstack(&s);initstack(&s1);
ch=getchar();
//clear(&s);
// for(i=6;i>=0;i--){
// printf("%c\n",gettop(&s));//pop(&s,&ch[1]);
// }
while(ch!=EOF&&ch!='\n'){
switch(ch){
case '#':pop(&s,&ch);break;
case '@' :clear(&s);break;
default :push(&s,ch);break;
}
ch=getchar();
}
while(s.top!=s.base){
*(s1.top)=gettop(&s);
//printf("%c",gettop(&s1));
s.top--;
s1.top++;
}
while(s1.top!=s1.base){
printf("%c",gettop(&s1));
s1.top--;
}
}
参考答案(时间最优[0]):
#include <stdio.h>
#include <stdlib.h>
#define STACK_INT_SIZE 100
typedef struct stu{
int *base;
int *top;
int stacksize;
}stack;
void initstack(stack *s){
s->base=s->top=(int *)malloc(STACK_INT_SIZE*sizeof(int));
s->stacksize=STACK_INT_SIZE;
}
void push(stack *s,char e){
*s->top++=e;
}
int pop(stack *s,char *e){
if(s->base==s->top)
return 0;
s->top--;
*e=*(s->top);
return 1;
}
void clear(stack *s)
{
s->base=s->top;
s->stacksize=0;
}
char gettop(stack *s)
{
return *(s->top-1);
}
void main()
{
stack s,s1;
char ch;
int i;
initstack(&s);initstack(&s1);
ch=getchar();
//clear(&s);
// for(i=6;i>=0;i--){
// printf("%c\n",gettop(&s));//pop(&s,&ch[1]);
// }
while(ch!=EOF&&ch!='\n'){
switch(ch){
case '#':pop(&s,&ch);break;
case '@' :clear(&s);break;
default :push(&s,ch);break;
}
ch=getchar();
}
while(s.top!=s.base){
*(s1.top)=gettop(&s);
//printf("%c",gettop(&s1));
s.top--;
s1.top++;
}
while(s1.top!=s1.base){
printf("%c",gettop(&s1));
s1.top--;
}
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。
