【c++习题】【17/4/13】stack

1、stack 模板、动态内存分配、析构

1
#include "stack2.cpp"

#include <iostream>
using namespace std;

int main()
{
    // 测试int型
    Stack<int> s1(5);
    s1.push(1);
    s1.push(2);
    s1.push(3);
    s1.push(4);
    s1.push(5);
    if(!s1.isEmpty()) cout << s1.pop() << endl;
    cout << s1.pop() << endl;
    cout << s1.pop() << endl;
    cout << s1.pop() << endl;
    cout << s1.pop() << endl;
    cout << endl;

    // 测试char型
    Stack<char> s2(6);
    if(!s2.isFull()) s2.push('a');
    s2.push('b');
    s2.push('c');
    s2.push('d');
    s2.push('e');
    s2.push('f');
    cout << s2.pop() << endl;
    cout << s2.pop() << endl;
    cout << s2.pop() << endl;
    cout << s2.pop() << endl;
    cout << s2.pop() << endl;
    //cout << s2.pop() << endl;
    return 0;
}

2

template <class T>
class Stack {
private:
    T *sptr;
    int size;
    int Top;
public:
    // 构造器
    Stack()
    {
        sptr = new T[10];
        size = 10;
        Top = 0;
    }
    Stack(int n)
    {
        sptr = new T[n];
        size = n;
        Top = 0;
    }
    // 析构函数
    ~Stack()
    {
        delete []sptr;
    }
    // push
    void push(T i)
    {
        *(sptr++) = i;
        ++Top;
    }
    // pop
    T pop()
    {
        return *(--sptr);
        --Top;
    }
    bool isEmpty()
    {
        if (Top == 0)
            return true;
        return false;
    }
    bool isFull()
    {
        if (Top < size)
            return false;
        return true;
    }
};

 

posted @ 2017-05-08 18:32  xkfx  阅读(286)  评论(0编辑  收藏  举报