---
# System prepended metadata

title: 阿強強 Stack 練習
tags: [資料結構]

---

###### tags: `資料結構`

# 阿強強 Stack 練習
```
#include <iostream>
#include <string>

using namespace std;

template <typename T>
class Stack{
    public:
        Stack(int InitCapacity);
        ~Stack();
        bool IsEmpty();
        void Push(T input);
        T    Top();
        void Pop();
    private:
        T *stack_array;
        int currentTop;
        int capacity;
};

template <typename T>
Stack<T>::Stack(int InitCapacity){
    cout << "=== create ===" << endl;
    stack_array = new T[InitCapacity];
    currentTop = -1;
    capacity = InitCapacity;
}

template <typename T>
Stack<T>::~Stack(){
    cout << "=== delete ===" << endl;
    delete[] stack_array;
}

template <typename T>
bool Stack<T>::IsEmpty(){
    if (currentTop==-1) return 1;
    else return 0;
}

template <typename T>
void Stack<T>:: Push(T input){
    stack_array[++currentTop] = input;
    cout << "Push: currentTop=" << currentTop << endl;
}

template<typename T>
T Stack<T>::Top(){
    return stack_array[currentTop];
}

template<typename T>
void Stack<T>:: Pop(){
    stack_array[currentTop--].~T();
    cout << "Pop: currentTop=" << currentTop << endl;
}


int main()
{
    Stack<int> a(10);
    cout << "IsEmpty: " << a.IsEmpty() << endl;
    cout << "Top:" << a.Top() << endl;
    a.Push(30);
    cout << "Top:" << a.Top() << endl;
    a.Pop();
    cout << "Top:" << a.Top() << endl;
    return 0;
}

// g++ -std=c++11 -Wall -pedantic -pthread main.cpp && ./a.out
```
![](https://i.imgur.com/NuJbz3v.png)

---
> [name=CHEN, KO-CHIANG]
> 
> [time=Sun, Feb 5, 2023 9:54 PM]
> 
> [reference link] 
> 
> 1. https://www.youtube.com/playlist?list=PLS0SUwlYe8cxbiGgUdK24o756wfbG3Xrw 