问题分析:
行编辑命令:输入一段话,若输入'#'则表示前一个无效,若输入'@'则表示这段话作废。
语言实现:
//头文件部分
#pragma once
#define STACK_SIZE 50
typedef char ElemType;
#include<iostream>
#include<assert.h>
using namespace std;
typedef struct Stack
{
ElemType *base;
int capacity;
int top;
}Stack;
/
bool Ful(Stack *sta)
{
return sta->top >= sta->capacity;
}
bool Init(Stack *sta)
{
sta->base = (ElemType *)malloc(sizeof(ElemType)*STACK_SIZE);
assert(sta->base != NULL);
sta->top = 0;
sta->capacity = STACK_SIZE;
return true;
}
bool push_stack(Stack *sta,ElemType x)
{
sta->base[sta->top++] = x;
return true;
}
bool pop_stack(Stack *sta)
{
if(sta->top == 0)
{
cout<<"the stack is empty"<<endl;
return false;
}
cout<<sta->base[sta->top-1];
sta->top--;
return true;
}
void show_stack(Stack *sta)
{
int i = 0;
while(i < sta->top)
{
cout<<sta->base[i];
i++;
}
cout<<";"<<endl;
}
void clear(Stack *sta)
{
sta->top = 0;
}
void delete_stack(Stack *sta)
{
sta->top--;
}
//主函数部分
#include"stack.h"
void main()
{
Stack myst;
char str;
char select;
Init(&myst);
while(select != '0')
{
cout<<"请输入并以','结束:";
while(cin>>str,str!= ',')
{
if(Ful(&myst))
{
cout<<"空间不够"<<endl;
return ;
}
if(str == '#')
delete_stack(&myst);
else if(str == '@')
clear(&myst);
else
push_stack(&myst,str);
}
push_stack(&myst,',');
show_stack(&myst);
cout<<"继续请选1,退出选择0:";
cin>>select;
}
return ;
}
分析:此问题是栈结构的一种应用,理解栈结构后很容易就能解决此问题。