template <class T>
class Stack
{
private :
T* stack;
T top;
int capacity;
public :
Stack();
Stack(int);
T Top();
void Push(T);
void Pop();
bool isEmpty();
bool isFull();
};
각 멤버 함수의 구현
Stack()
template <class T>
Stack<T>::Stack()
{
this->capacity = 10;
this->stack = new T[this->capacity];
this->top = -1;
}
template <class T>
Stack<T>::Stack(int capacity)
{
this->capacity = capacity;
this->stack = new T[this->capacity];
this->top = -1;
}
template <class T>
T Stack<T>::Top()
{
T ret = NULL;
if (!this->isEmpty())
{
ret = this->stack[top];
}
return ret;
}
template <class T>
void Stack<T>::Push(T data)
{
if (!this->isFull())
{
this->stack[++top] = data;
}
}
template <class T>
void Stack<T>::Pop()
{
if (!this->isEmpty())
{
this->top--;
}
}
template <class T>
bool Stack<T>::isEmpty()
{
if (this->top == -1)
{
return true;
}
return false;
}
template <class T>
bool Stack<T>::isFull()
{
if (this->top == (this->capacity - 1))
{
return true;
}
return false;
}
#include <iostream>
using namespace std;
template <class T>
class Stack
{
private :
T* stack;
T top;
int capacity;
public :
Stack();
Stack(int);
T Top();
void Push(T);
void Pop();
bool isEmpty();
bool isFull();
};
template <class T>
Stack<T>::Stack()
{
this->capacity = 10;
this->stack = new T[this->capacity];
this->top = -1;
}
template <class T>
Stack<T>::Stack(int capacity)
{
this->capacity = capacity;
this->stack = new T[this->capacity];
this->top = -1;
}
template <class T>
T Stack<T>::Top()
{
T ret = NULL;
if (!this->isEmpty())
{
ret = this->stack[top];
}
return ret;
}
template <class T>
void Stack<T>::Push(T data)
{
if (!this->isFull())
{
this->stack[++top] = data;
}
}
template <class T>
void Stack<T>::Pop()
{
if (!this->isEmpty())
{
this->top--;
}
}
template <class T>
bool Stack<T>::isEmpty()
{
if (this->top == -1)
{
return true;
}
return false;
}
template <class T>
bool Stack<T>::isFull()
{
if (this->top == (this->capacity - 1))
{
return true;
}
return false;
}
int main()
{
cout << "capacity가 70인 Stack 생성\n";
Stack<int> stack(70);
if (stack.isEmpty())
{
cout << "stack이 비어있습니다.\n";
}
cout << "0부터 34까지 stack에 push합니다\n";
for (int i = 0; i < 35; i++)
{
stack.Push(i);
}
cout << "stack의 Top : " << stack.Top() << '\n';
cout << "35부터 69까지 stack에 push합니다\n";
for (int i = 35; i < 70; i++)
{
stack.Push(i);
}
cout << "stack의 Top : " << stack.Top() << '\n';
if (stack.isFull())
{
cout << "stack이 꽉 찼습니다.\n";
}
cout << "stack에서 15개의 데이터를 pop합니다\n";
for (int i = 0; i < 15; i++)
{
stack.Pop();
}
cout << "stack의 Top : " << stack.Top() << '\n';
}
capacity가 70인 Stack 생성
stack이 비어있습니다.
0부터 34까지 stack에 push합니다
stack의 Top : 34
35부터 69까지 stack에 push합니다
stack의 Top : 69
stack이 꽉 찼습니다.
stack에서 15개의 데이터를 pop합니다
stack의 Top : 54