栈+链式

// LinkStackMain.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>       //引用输入输出流
using namespace std;
template <class T>
struct Node
{
    T data;
    Node<T> *next;  //此处<T>也可以省略
};

template <class T>
class LinkStack
{
public:
    LinkStack();              //构造函数,置空链栈
    ~LinkStack();             //析构函数,释放链栈中各结点的存储空间
    void Push(T x);           //将元素x入栈
    T Pop();                  //将栈顶元素出栈
    T GetTop();               //取栈顶元素(并不删除)
    bool Empty();             //判断链栈是否为空栈
    void PrintLink();
private:
    Node<T> *top;             //栈顶指针即链栈的头指针
};

template <class T>
LinkStack<T>::LinkStack()
{
    top = NULL;
}

template <class T>
LinkStack<T>::~LinkStack()
{
    while (top)
    {
        Node<T> *p;
        p = top->next;
        delete top;
        top = p;
    }
}

template<class T>
void LinkStack<T>::Push(T x)
{
    Node<T> *s;
    s = new Node<T>;
    s->data = x;
    s->next = top;
    top = s;
}

template<class T>
T LinkStack<T>::Pop()
{
    T x;
    Node<T> *p;
    if (top == NULL)
        throw"下溢";
    x = top->data;
    p = top;
    top = top->next;
    delete p;
    return x;

}

template <class T>
T LinkStack<T>::GetTop()
{
    if (top != NULL)
        return top->data;
}

template <class T>
bool LinkStack<T>::Empty()
{
    if (top == NULL)
        return 1;
    else
        return 0;
}

template <class T>
void LinkStack<T>::PrintLink()
{
    Node<T> *p = top;
    while (p != NULL)
    {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    LinkStack<int>a;             //创建模板类的实例
    if (a.Empty())
    {
        cout << "栈空,执行操作" << endl;
        cout << "对 15 、10、5、0、-5栈进行压栈操作:" << endl;
        try
        {
            a.Push(15);
            a.Push(10);
            a.Push(5);
            a.Push(0);
            a.Push(-5);
        }
        catch (char *wrong)
        {
            cout << wrong<<endl;
        }
        cout << "栈内元素为:";
        a.PrintLink();
        cout << "读取栈顶元素:\n";
        cout << a.GetTop() << endl;
        cout << "进行出栈操作:" << endl;    //出栈操作 
        a.Pop();
        cout << "读取栈顶元素:" << endl;
        cout << a.GetTop() << endl;
    }
    else
    {
        cout << "栈不空" << endl;
    }
    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值