老師在 CEIBA 給的 Stack list ADT (stack.cpp) 實作,我只在最後面多加了幾行
// 只多加下面幾行
try{
aStack.pop();
}
catch (StackException e){
cout << e.what();
}
=> 1
=> 2
=> 3
=> empty pop
// 只多加下面幾行
try{
aStack.pop();
}
catch (StackException e){
cout << e.what();
}
=> 1
=> 2
=> 3
=> empty pop
#include <iostream> | |
#include <stdexcept> | |
#include <string> | |
using namespace std; | |
const int MAX_STACK = 50; | |
typedef int StackItemType; | |
class StackException: public exception | |
{ | |
private: | |
string msg; | |
public: | |
StackException(const string & message =""):msg(message) {} | |
~StackException() throw(){}; | |
const char* what() const throw() { return msg.c_str(); } | |
}; | |
class Stack | |
{ | |
public: | |
Stack(); | |
~Stack(); | |
Stack(const Stack&); | |
bool isEmpty(); | |
void push(const StackItemType& ) throw (StackException); | |
void pop() throw(StackException); | |
StackItemType getTop() throw(StackException); | |
private: | |
struct StackNode | |
{ | |
StackItemType item; | |
StackNode *next; | |
}; | |
StackNode *topPtr; | |
}; | |
// default constructor. | |
Stack::Stack() : topPtr(NULL) {} | |
// destructor | |
Stack::~Stack() | |
{ | |
while(!isEmpty()) | |
pop(); | |
} | |
// copy constructor. | |
Stack::Stack(const Stack& aStack) | |
{ | |
if(aStack.topPtr == NULL) | |
topPtr = NULL; | |
else | |
{ // copy first node | |
topPtr = new StackNode; | |
topPtr->item = aStack.topPtr->item; | |
// copy rest of list | |
StackNode *newPtr = topPtr; | |
for(StackNode *origPtr = aStack.topPtr->next; | |
origPtr != NULL; | |
origPtr = origPtr->next) | |
{ | |
newPtr->next = new StackNode; | |
newPtr = newPtr->next; | |
newPtr->item = origPtr->item; | |
} // end for | |
newPtr->next = NULL; | |
} // end if | |
} // end copy constructor | |
bool Stack::isEmpty(){ | |
return topPtr==NULL; | |
} | |
void Stack::push(const StackItemType& newItem) throw (StackException) | |
{ try { | |
StackNode *newPtr = new StackNode; | |
newPtr->item = newItem; | |
newPtr->next = topPtr; | |
topPtr = newPtr; | |
} catch (bad_alloc e) { throw StackException("push failed"); } | |
} | |
void Stack::pop() throw(StackException) | |
{ | |
if(isEmpty()) | |
throw StackException("empty pop"); | |
else | |
{ | |
StackNode *temp = topPtr; | |
topPtr = topPtr->next; | |
temp->next = NULL; | |
delete temp; | |
} | |
} | |
StackItemType Stack::getTop() throw(StackException) | |
{ | |
if(isEmpty()) | |
throw StackException("empty stack"); | |
else | |
{ | |
return topPtr->item; | |
} | |
} | |
int main() | |
{ | |
StackItemType anItem; // typedef int StackItemType; | |
Stack aStack; | |
aStack.push(1); | |
aStack.push(2); | |
aStack.push(3); | |
cout<<aStack.getTop()<<endl; | |
aStack.pop(); | |
cout<<aStack.getTop()<<endl; | |
aStack.pop(); | |
cout<<aStack.getTop()<<endl; | |
aStack.pop(); | |
// 只多加下面幾行 | |
try{ | |
aStack.pop(); | |
} | |
catch (StackException e){ | |
cout << e.what(); | |
} | |
system("pause"); | |
} | |