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

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值