1 数组栈写法
#include <iostream>
#include <string>
using namespace std;
typedef string T;
class Stack
{
T a[5];//如果是固定的直接写个数组
int cur;
public:
Stack():cur(0){}
//对象没有占用其他资源如打开文件 动态分配内存等 所以不需要析构
void push(const T&) throw(const char*);//数据入栈顶
T pop() throw(const char*) ;//栈顶数据出栈 下一个成为栈顶
const T& top() const throw(const char*) ;//取得栈顶数据
bool empty() const; //是否为空
bool full() const;//是否已满
void clear();//清空栈
int size() const ;//栈元素个数
};
void Stack::push(const T& d) throw(const char*) //异常声明要在函数声明和函数体中都要有
{
if( full() ) throw "堆栈满";
a[cur++] = d;
}
T Stack::pop() throw(const char*)
{
if( empty() ) throw "堆栈空";
return a[--cur];
}
const T& Stack:: top() const throw(const char*)
{
if( empty() ) throw "堆栈空";
return a[cur-1];
}
bool Stack::empty() const
{
return cur==0;
}
bool Stack::full() const
{
return cur==5;
}
void Stack::clear()
{
cur =0;
}
int Stack::size() const
{
return cur;
}
int main()
{
Stack s;
try
{
s.push("hello world");//c风格字符串能自动转换成string类型
s.push("good morning");
s.push("芙蓉");
s.push("春哥");
s.push("权哥");
s.push("明哥"); //多出来了一个
}
catch(const char * str)
{
cerr << "出错:" << str << endl;
}
while(!s.empty())
{
cout << s.pop() << endl;
}
}
2 链表栈写法
#include <iostream>
#include <string>
#include "02list.h"
using namespace std;
typedef int T; //目前这个类型要和链表中定义的一样 其实用模板更好点
class Stack
{
List l;
public:
void push(const T&);//数据入栈顶
T pop() ;//栈顶数据出栈 下一个成为栈顶
T top() const ;//取得栈顶数据
bool empty() const; //是否为空
void clear();//清空栈
int size() const ;//栈元素个数
};
void Stack::push(const T& d)
{
l.push_front(d);//从链表前面进行插入
}
//链表中做了出错处理 异常处理 所以不必再做这个了
T Stack::pop()// throw(const char*)
{
//if( empty() ) throw "堆栈空";
T t = l.front();//链表第一个元素
l.erase(0);//删除链表第一个元素
return t;
}
T Stack:: top() const //throw(const char*)
{
//if( empty() ) throw "堆栈空";
return l.front();//返回最前面的元素
}
bool Stack::empty() const
{
return l.empty();
}
void Stack::clear()
{
l.clear();
}
int Stack::size() const
{
return l.size();
}
int main()
{
Stack s;
s.push(1);//c风格字符串能自动转换成string类型
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
while(!s.empty())
{
cout << s.pop() << endl;
}
try
{
cout << s.top() << endl;
//链表会产生异常
}
catch(const char * str)
{
cerr << "出错:" << str << endl;
}
}
02list.h及02list.cpp见http://blog.csdn.net/a8887396/article/details/8867696