用C++实现一个简单栈,基于链表:
#ifndef _LINKEDSTACK_
#define _LINKEDSTACK_
#include <iostream>
#include <stdexcept>
using namespace std;
template <typename T>
class LinkedStack
{
public:
LinkedStack() : _size(0), _head(NULL) {}
~LinkedStack() { Clear(); }
LinkedStack(const LinkedStack& rhs) : _head(NULL)
{
operator= (rhs);
}
const LinkedStack& operator= (const LinkedStack& rhs)
{
if( this != &rhs )
{
Clear();
LinkedStackNode* temp = rhs._head;
LinkedStackNode* tail = NULL;
while(temp != NULL)
{
if(_size == 0)
{
// first added node
_head = new LinkedStackNode(temp->data,NULL);
tail = _head;
}
else
{
tail->next = new LinkedStackNode(temp->data,NULL);
tail = tail->next;
}
++_size;
temp = temp->next;
}
}
return *this;
}
int Size() const { return _size; }
bool IsEmpty() const { return _size == 0; }
void Print() const
{
cout<< "Size=" << _size <<endl;
LinkedStackNode* temp = _head;
while(temp != NULL)
{
cout << temp->data <<",";
temp = temp->next;
}
cout << endl;
}
void Clear()
{
_size = 0;
LinkedStackNode* temp = _head;
while(temp != NULL)
{
_head = temp->next;
delete temp;
temp = _head;
}
}
void Push(const T& value)
{
// when stack is empty, _head is NULL
// so we can use this to handle empty stack and non-empty stack situation
_head = new LinkedStackNode(value,_head);
++_size;
}
T Pop()
{
if(IsEmpty())
throw logic_error("Stack is empty");
LinkedStackNode* temp = _head;
T value = temp->data;
_head = _head->next;
--_size;
delete temp;
return value;
}
T& Top() const
{
if(IsEmpty())
throw logic_error("Stack is empty");
return _head->data;
}
private:
class LinkedStackNode
{
public:
T data;
LinkedStackNode* next;
LinkedStackNode(const T& v,LinkedStackNode* n=NULL): data(v),next(n) {}
};
private:
int _size;
LinkedStackNode* _head;
};
#endif
测试代码:
#include "LinkedStack.cpp"
void LinkedStackTest1();
void Test( void (*fp)() );
int main(int argc, char** argv)
{
Test(LinkedStackTest1);
return 0;
}
void LinkedStackTest1()
{
LinkedStack<int> s;
s.Print();
s.Push(5);
s.Print();
s.Push(4);
s.Push(3);
s.Push(2);
s.Push(1);
s.Print();
cout << "Top=" << s.Top() << endl;
cout << "Pop=" << s.Pop() << endl;
s.Print();
cout<< "s2 content:" << endl;
LinkedStack<int> s2;
s2.Push(10);
s2.Print();
s2 = s;
s2.Print();
s.Clear();
s2.Print();
cout << "Pop=" << s2.Pop() << endl;
cout << "Pop=" << s2.Pop() << endl;
cout << "Pop=" << s2.Pop() << endl;
cout << "Pop=" << s2.Pop() << endl;
s2.Print();
cout<< "s content:" << endl;
s.Print();
}
void Test( void (*fp)() )
{
try
{
fp();
}
catch(out_of_range e)
{
cout<< "Catch Exception:" << e.what() << endl;
}
catch(overflow_error e)
{
cout<< "Catch Exception:" << e.what() << endl;
}
catch(logic_error e)
{
cout<< "Catch Exception:" << e.what() << endl;
}
}