您的位置:首页 > 理论基础 > 数据结构算法

链栈,C++,数据结构王红梅版

2014-12-23 22:51 225 查看
#ifndef _LINKSTACK_H_

#define _LINKSTACK_H_

#include "LinkStack.h"

#include<iostream>

using namespace std;

template<class DataType>

struct Node //链栈节点

{

DataType data; //节点数据域

Node<DataType> *next; //节点指针域

};

template<class DataType>

class LinkStack

{

public:

LinkStack(); //构造函数

~LinkStack(); //析构函数

void Push(DataType x); //压栈

void Pop(); //弹栈

DataType GetTop(); //得到栈顶元素

bool isEmpty(); //判断栈是否为空

private:

Node<DataType> *top; //栈顶指针

};

template<class DataType>

LinkStack<DataType>::LinkStack()

{

top=NULL; //栈初始化为空

}

template<class DataType>

LinkStack<DataType>::~LinkStack()

{

Node<DataType> *p; //栈顶指针

p=top;

while(top!=NULL)

{

top=p->next; //栈顶指针后移,相当于top--

delete p; //将栈顶节点删除

p=top;

}

}

template<class DataType>

void LinkStack<DataType>::Push(DataType x)

{

Node<DataType> *p; //栈顶节点

p=new Node<DataType>;

p->data=x;

p->next=top;

top=p;

}

template<class DataType>

void LinkStack<DataType>::Pop()

{

Node<DataType> *p;

p=top;

top=top->next;

DataType x;

x=p->data;

delete p;

cout<<x<<" ";

}

template<class DataType>

DataType LinkStack<DataType>::GetTop()

{

DataType x;

x=top->data;

return x;

}

template<class DataType>

bool LinkStack<DataType>::isEmpty()

{

return top==NULL;

}

#endif // _LINKSTACK_H_

#include "LinkStack.h"

int main()

{

LinkStack<int> link;

int i=0;

for(;i!=3;i++)

{

link.Push(i);

}

for(;i!=3;++i)

{

link.Pop();

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: