数据结构:栈
2009-03-09 13:43 Iron 阅读(134) 评论(0) 编辑 收藏 举报#include <vld.h>//测试内存泄露
#include <iostream>
#include <string>
#include <sstream>//整型到string的转化类库
using namespace std;
//栈节点定义
class Node
{
public:
int data;
Node* pre;
Node* next;
Node(int n):data(n),pre(NULL),next(NULL)//初始化
{
}
};
//栈
class stack
{
public:
Node* top;//栈顶指针
Node* bottom;//栈底指针
int length;//栈中的元素个数
stack():length(0),top(NULL),bottom(NULL)//初始化栈
{}
bool push(int x);//向栈压入一个元素
Node pop();//弹出一个元素,并返回它
Node getTop();//得到栈顶元素
string toString();//将栈中的元素取出来连成字符串
~stack();//析构每一个元素
};
bool stack::push(int x)
{
Node* tempNode = new Node(x);
if(0 == length)
{
bottom = top = tempNode;
length++;
return true;
}
else
{
Node* tempTop = top;
top = tempNode;
top->pre = tempTop;
tempTop->next = top;
length++;
}
return true;
}
//弹出栈顶元素
Node stack::pop()
{
Node* tempTop = top;
Node tempNode = *top;
top = top->pre;
delete tempTop;
length--;
return tempNode;
}
Node stack::getTop()
{
return *top;
}
string stack::toString()
{
string s = "";
Node* iterator = bottom;
for(;;)
{
stringstream ss;
ss<<iterator->data;
s += ss.str()+" ";
if(NULL == iterator->next)break;//如果下一个元素为NULL则跳出
iterator = iterator->next;
}
return s;
}
//析构函数
stack::~stack()
{
//析构申请的内存
for(int i = length; i > 0; i--)
{
cout<< "删除了" << getTop().data <<endl;
pop();
}
}
int main()
{
stack* myStack = new stack();
myStack->push(12);
myStack->push(23);
myStack->push(12);
myStack->push(23);
myStack->push(12);
myStack->push(23);
myStack->push(12);
myStack->push(23);
cout << myStack->toString() << endl;
myStack->pop();
cout << "Total nums:" << myStack->length << endl;
delete myStack;
return 0;
}