[04. 스택과 큐] Stack 구현

DongWook Lee·2024년 7월 23일
class Stack {
	int max;
	int top;
	int* stk;
public:
	Stack(int max=10) : max(max), top(0), stk(new int[max]) {}
	~Stack() { delete[] stk; }

	bool Push(int x) {
		if (IsFull()) return false;
		stk[top++] = x;
		return true;
	}
	int Pop()				{ return stk[--top]; }		// top == 0 이면 error발생
	void Clear()			{ top = 0; }
	int Search(int x) const {
		for (int i = top - 1; i >= 0; i--)
			if (stk[i] == x) return i;
		return -1;
	}
	bool IsFull() const		{ return top >= max; }
	bool IsEmpty() const	{ return top == 0; }
	int Peek() const		{ return stk[top-1]; }		// top == 0 이면 error발생
	int Capacity() const	{ return max; }
	int Size() const		{ return top; }
};
#include <iostream>
using namespace std;

int main() {
	Stack s;
	s.Push(3);
	s.Push(9);
	s.Push(54);
	while (!s.IsFull())
		s.Push(1);
	cout << s.Peek() << endl;		// 1
	cout << s.Pop() << endl;		// 1
	cout << s.Search(54) << endl;	// 2

	while (!s.IsEmpty())
		s.Pop();
	cout << s.Capacity() << endl;	// 10
	cout << s.Size() << endl;		// 0
}

0개의 댓글