1013: 链式栈
Description
已知链栈类的定义、构造函数及main函数如下,请完成其余的成员函数实现。
template <class T>
class LinkStack
{
public:
LinkStack( ); //构造函数,置空链栈
~LinkStack( ); //析构函数,释放链栈中各结点的存储空间
void Push(T x); //将元素x入栈
T Pop( ); //将栈顶元素出栈
T GetTop( ); //取栈顶元素(并不删除)
bool Empty( ); //判断链栈是否为空栈
private:
Node<T> *top; //栈顶指针即链栈的头指针
};
/*
* 前置条件:栈不存在
* 输 入:无
* 功 能:栈的初始化
* 输 出:无
* 后置条件:构造一个空栈
*/
template <class T>
LinkStack<T>::LinkStack( )
{
top=NULL;
}
int main()
{
LinkStack<char> s;
char ch;
while(1)
{
cin>>ch;
if(ch=='#') break;
s.Push(ch);
}
cout<<"Gettop:"<<s.GetTop()<<endl;
while(!s.Empty())
{
cout<<s.Pop()<<" ";
}
cout<<endl;
try{
cout<<"Gettop:"<<s.GetTop()<<endl;
}
catch(const char *ms){
cout<<"Gettop:"<<ms<<endl;
}
return 0;
}
Input
Output
Sample Input
asdfgh#
Sample Output
Gettop:h h g f d s a Gettop:Downflow
//
// Created by Legends丶Hu on 2020/2/4.
//
#include <iostream>
using namespace std;
template<class T>
struct Node {
T data;
Node<T> *next;
};
template<class T>
class LinkStack {
public:
LinkStack(); //构造函数,置空链栈
~LinkStack(); //析构函数,释放链栈中各结点的存储空间
void Push(T x); //将元素x入栈
T Pop(); //将栈顶元素出栈
T GetTop(); //取栈顶元素(并不删除)
bool Empty(); //判断链栈是否为空栈
private:
Node<T> *top; //栈顶指针即链栈的头指针
};
template<class T>
LinkStack<T>::LinkStack() {
top = NULL;
}
template<class T>
LinkStack<T>::~LinkStack() {
while (top) {
Node<T> *p = top;
top = top->next;
delete p;
}
}
template<class T>
void LinkStack<T>::Push(T x) {
Node<T> *s = new Node<T>;
s->data = x;
s->next = top;
top = s;
}
template<class T>
T LinkStack<T>::Pop() {
if(top == NULL) throw "Downflow";
T x = top->data;
Node<T> *p = top;
top = top->next;
delete p;
return x;
}
template<class T>
T LinkStack<T>::GetTop() {
if (top == NULL) throw "Downflow";
return top->data;
}
template<class T>
bool LinkStack<T>::Empty() {
return top == NULL;
}
int main() {
LinkStack<char> s;
char ch;
while (1) {
cin >> ch;
if (ch == '#') break;
s.Push(ch);
}
cout << "Gettop:" << s.GetTop() << endl;
while (!s.Empty()) {
cout << s.Pop() << " ";
}
cout << endl;
try {
cout << "Gettop:" << s.GetTop() << endl;
}
catch (const char *ms) {
cout << "Gettop:" << ms << endl;
}
return 0;
}