使用链表实现堆栈,不需要考虑容量问题,所以只需要注意链表是否为空
#include<iostream>
#include<fstream>
using namespace std;
class Stack{
public:
Stack(void):top(NULL){}
~Stack(void){
for(Node *p;top;top=p){
p=top->next;
delete top;
}
}
void push(int pdata){
// Node *p=new Node;
// p->data=pdata;
// p->next=top;
// top=p;
top=new Node(pdata,top);
}
int pop(void){
if(empty())
throw UnderFlow();
int pdata=top->data;
Node *p=top->next;
delete top;
top=p;
return pdata;
}
bool empty(){
return !top;
}
private:
class UnderFlow:public exception{
const char* what()const throw(){
return "链表下溢";
}
};
class Node{
public:
Node(int pdata=,Node *pnext=NULL):data(pdata),next(pnext){}
int data;
Node *next;
};
Node *top;
};
int main(){
int fi;
ofstream ofs("data.dat");
try{
Stack stack;
for(int i=;i<=;i++){
stack.push(i);
}
while(!stack.empty()){
fi=stack.pop();
ofs.write((char *)&fi,sizeof(int));
}
ofs.close();
//
// ifstream ifs("data.dat");
// while(!ifs.eof()){
// ifs.read((char *)&fi,sizeof(int));
// cout << fi << ' ';
// }
// cout << endl;
// ifs.close();
// cout<<stack.pop()<<endl;
}
catch(exception& ex){
cout <<ex.what()<<endl;
return -;
}
}