65,187
社区成员




// stack.h
// stack头文件
#ifndef stack_h
#define stack_h
#include<iostream>
using namespace std;
enum Error_code {underflow,success,overflow};
template <typename Stack_entry>
class Stack
{
public:
Stack(int len) : count(0), size(len), entry(new Stack_entry[size]) {}
~ Stack() { delete [] entry; }
bool empty() const;
Error_code pop();
Error_code top( Stack_entry &item ) const;
Error_code push(const Stack_entry &item);
private:
int count;
int size;
Stack_entry * entry;
};
#endif
// stack.cpp
// stack的具体实现文件
#include<iostream>
#include "stack.h"
using namespace std;
template <class Stack_entry>
bool Stack<Stack_entry> :: empty() const
/*Pre: None.
Post:If the stack is empty, true is returned. Otherwisw false is returned.*/
{
return count == 0 ? true : false;
}
template <class Stack_entry>
Error_code Stack<Stack_entry> :: pop()
/*Pre: None.
Post:If the stack is not empty, the top of the stack is removed.
If the stack is empty, an Error_code of underflow is returned.*/
{
Error_code outcome = success;
if (count == 0)
outcome = underflow;
else
cout << entry[count--];
return outcome;
}
template <class Stack_entry>
Error_code Stack<Stack_entry> :: push(const Stack_entry &item)
/*Pre: None.
Post:If the stack is not full, item is added to the top of the stack..
If the stack is full, an Error_code of overflow is returned.*/
{
Error_code outcome = success;
if (count > size)
outcome = overflow;
else
entry[count++] = item;
return outcome;
}
template <class Stack_entry>
Error_code Stack<Stack_entry> :: top(Stack_entry &item) const
/*Pre: None.
Post:If the stack is not empty, the top of the stack is returned in item.
If the stack is empty, an Error_code of underflow is returned.*/
{
Error_code outcome = success;
if(count == 0)
outcome = underflow;
else
item = empty[count-1];
return outcome;
}
/* 程序目的:
用模板形式将动态数组存储的栈实现
在主函数中将栈实例化
完成指定输入输出测试程序
*/
#include<iostream>
#include"stack.h"
using namespace std;
int main()
{
Stack<char> data(3);
data.push('a');
data.push('b');
data.push('c');
data.pop();
data.pop();
data.pop();
return 0;
}