数据结构没写完的习题

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

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

template<class T>
struct Node {
    T data;
    Node<T> *next;
};

template<class T>
class LinkStack {
public:
    LinkStack();
    ~LinkStack();
    void Push(T x);
    T Pop();
    T GetTop();
    bool Empty();
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 = new Node<T>;
    s->data = x;
    s->next = top;
    top = s;
}

template<class T>
T LinkStack<T>::Pop() {
    T x;
    Node<T> * p = top;
    x = top->data;
    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;
}
void main()
{
    LinkStack<int>a;
    if (a.Empty()) {
        cout << "栈空,执行操作" << endl;
        cout << "对 10进行压栈操作:" << endl;
        try {
            a.Push(10);
        }
        catch (char *wrong) {
            cout << wrong;
        }
        cout << "读取栈顶元素:" << endl;
        cout << a.GetTop() << endl;
        cout << "对15栈进行压栈操作:" << endl;
        try {
            a.Push(15);
        }
        catch (char *wrong) {
            cout << wrong;
        }
        cout << "读取栈顶元素:\n";
        cout << a.GetTop() << endl;
        cout << "进行出栈操作:" << endl;
        a.Pop();
        cout << "读取栈顶元素:" << endl;
        cout << a.GetTop() << endl;
    }
    else {
        cout << "栈不空" << endl;
    }
    a.~LinkStack();
    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值