IT 프로그래밍/자료구조
[자료구조] class ArrayStack
기술1
2024. 10. 15. 20:12
const int MAX_CAPACITY = 100;
class ArrayStack
{
private:
char stack[MAX_CAPACITY];
int top_pos = -1;
public:
bool full()
{
return top_pos = MAX_CAPACITY - 1;
}
bool empty()
{
return top_pos == -1;
}
void push(char c)
{
if (full())
throw runtime_error("stack_full");
stack[++top_pos] = c;
}
void pop()
{
if (empty())
throw runtime_error("stack_empty");
top_pos--;
}
char top()
{
if (empty())
throw runtime_error("stack_empty");
return stack[top_pos];
}
};
int main()
{
ArrayStack s1, s2;
s1.push('a');
s2.push('x');
cout << s1.top() << ' ' << s2.top() << endl;
if (!s1.empty())
s1.pop();
return 0;
}
클래스 ArrayStack
ArrayStack의 사용자는 public멤버함수만을 이용해서 작업을 합니다. 즉 배열 stack이나 top_pos 등에 직접 접근할 수 없습니다. arraystack으로 동시에 여러 개의 스택을 만들어 사용할 수 있습니다.
ArrayStack은 크기 제한을 가집니다. 최대 MAX_CAPACITY개의 데이터만 저장할 수 있습니다. 여전히 ArrayStack에는 한 유형의 데이터만 저장할 수 있습니다.
class Node
{
friend class LinkedStack;
private:
int data;
Node* next;
Node() {}
Node(int c, Node *p): data(c), next(p) {}
};
class LinkedStack
{
private:
Node* head = nullptr;
public:
bool full()
{
return false;
}
bool empty()
{
return head == nullptr;
}
void push(int c)
{
head = new Node(c, head);
}
void pop()
{
if (empty())
throw runtime_error("stack_empty");
Node* tmp = head;
head = head->next;
delete tmp;
}
int top()
{
if (empty())
throw runtime_error("stack_empty");
return head->data;
}
};
int main()
{
LinkedStack s1, s2;
s1.push(1);
s2.push(2);
cout << s1.top() << ' ' << s2.top() << endl;
}
LinkedStack의 사용자 역시 public 멤버함수만을 이용해서 작업을 합니다. 즉 포인터 head나 노드 내부에 직접 접근할 수 없습니다. 하지만 이 코드는 LinkedStack 클래스는 최소한의 destructor를 가지고 있어야 합니다.
메모리 누수 문제를 고려한다면 복사 생성자, 복사 치환 연산자, 특히 destructor가 필요합니다. 여전히 Linkedstack에는 한 유형의 데이터만 저장할 수 있습니다.