问题描述 :
目的:使用C++模板设计顺序栈的抽象数据类型(ADT)。并在此基础上,使用顺序栈ADT的基本操作,设计并实现简单应用的算法设计。
内容:(1)请参照顺序表的ADT模板,设计顺序栈的抽象数据类型。(由于该环境目前仅支持单文件的编译,故将所有内容都集中在一个源文件内。在实际的设计中,推荐将抽象类及对应的派生类分别放在单独的头文件中。参考教材、课件,以及网盘中的顺序表ADT原型文件,自行设计顺序栈的ADT。)
(2)ADT的简单应用:使用该ADT设计并实现若干应用顺序栈的算法设计。
应用1:要求设计一个算法,使用顺序栈,实现键盘输入字符序列逆置输出的算法设计。比如,从键盘上输入:tset a si sihT;算法将输出:This is a test。要求:输入的字符串长度在所建的顺序栈的有效空间范围内是可变的。
(1)顺序栈ADT版本
参考函数原型:
template<class ElemType>
void Invert_Input( SqStack<ElemType> &S ); (为简便起见,字符串输入可在该函数内一并实现)
顺序栈ADT类原型参考如下:
const int MAXLISTSIZE = 100;
template<class ElemType>
class SqStack{
private:
ElemType *base; // 栈底指针
ElemType *top; // 栈顶指针
int maxSize; // 允许的最大存储容量(以sizeof(ElemType)为单位
public:
//初始化顺序栈
SqStack(int ms = 20);
//删除顺序栈
~SqStack(){StackDestroy();}
//将顺序栈置为空表
bool StackClear( );
//返回顺序栈的长度
int StackLength() const {return top - base;}
//设置顺序栈的长度
//bool SetListLength(int len);
//判断顺序栈是否为空栈
bool StackisEmpty() const{ return top == base; }
//判断顺序栈是否为满栈
bool StackFull() const;
//用e返回栈顶元素
bool GetTop(ElemType &e) const;
//入栈
bool push(ElemType &e);
//出栈
bool pop(ElemType &e);
//销毁顺序栈
bool StackDestroy();
//遍历顺序栈
void StackTraverse() const;
//栈空间加倍
bool DoubleSpace();
};
(2)STL中stack版本
参考函数原型:
template<class ElemType1,class ElemType2>
void Invert_Input( stack<ElemType> &S ); (为简便起见,字符串输入可在该函数内一并实现)
输入说明 :
第一行:输入字符串
输出说明 :
第一行:输出的逆置字符串
输入范例 :
.tset a si sihT
输出范例 :
This is a test.
解题代码:
// 栈.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <sstream>
#include <stack>
#include <map>
#include <ctime>
#include <set>
using namespace std;
int main()
{
int i, j;
stack<char> s;
char c;
while ((c = getchar()) != EOF)
{
s.push(c);
}
while (!s.empty())
{
putchar(s.top());
s.pop();
}
return 0;
}