티스토리 뷰

공부

[DataStructure] Stack?

승가비 2018. 9. 7. 16:54
728x90

[DataStructure] Stack?


Stack 직접 구현해보기.

- push, pop, top

- new / delete

- Constructor / Destructor


// Stack 직접 구현해보기
// Class, Generic Class
// Array 동적할당 new / free
// Constructor / Destructor

#include <iostream>
using namespace std;

#define SIZE 1000000

template <class T>
class Stack {
private:
int pos = 0;
T *stack;

public:
Stack(int size) {
stack = new T[size];
}

~Stack(int size) {
delete stack;
}

T top() {
if(isEmpty()) {
cout << -1 << endl;
}

return stack[pos];
}

T pop() {
if(isEmpty()) {
cout << -1 << endl;
return NULL;
}

return stack[pos--];
}

void push(T n) {
stack[++pos] = n;
}

bool isEmpty() {
return pos == 0;
}
};

int main() {
Stack<int> *s = new Stack<int>(SIZE);

s->push(1);
s->push(2);
cout << s->pop() << endl;
s->push(3);
cout << s->pop() << endl;
cout << s->top() << endl;
cout << s->pop() << endl;

return 0;
}


728x90
댓글