2023. 7. 2. 11:09ㆍ자료 구조 및 알고리즘
설명 :
스택(stack)은 "쌓아놓은 더미"를 의미한다.
방금 들어온 것이 먼저 나가는 그런 구조를 생각하면 된다. (Last In, First Out)
흡사 "프링글즈 통"을 생각하면 이해하기 쉽다.
실생활 어느 곳에 쓰이는 지 예시를 들어보면,
대표적인 곳으로 문서나 인터넷 사용 시 되돌리기 기능을 사용할 떄라고 생각하면 된다.
코드 :
stack.cpp :
#include <iostream>
using namespace std;
class Stack
{
private:
int top;
int MaxSize;
char* stack;
public:
//1. 기본 구조와 상태를 판단 해주는 함수
Stack(int size); //생성자 함수
bool isFull(); //스택 구조가 가득 차 있는지
bool isEmpty(); //스택 구조가 비어있는지
//2. 자료를 넣어주거나 빼주는 함수
void push(char element); //스택 구조에 넣어주기
char pop(); //스택 구조에서 뺴기
//3. 출력 함수
void print(); //스택 구조 안 내용물 출력
};
Stack::Stack(int size) //생성자 함수 구현
{
MaxSize = size;
stack = new char[MaxSize];
top = -1;
}
bool Stack::isFull() //자료구조가 다 차있는지
{
if (top == MaxSize - 1) {
return true;
}
else {
return false;
}
}
bool Stack::isEmpty() //자료구조가 다 비어있는지
{
if (top == -1) {
return true;
}
else {
return false;
}
}
void Stack::push(char element) //자료를 구조에 집어넣기
{
if (isFull() == true)
{
cout << "Full!~" << endl;
}
else
{
stack[++top] = element;
}
}
char Stack::pop() //자료를 구조에서 뺴기
{
if (isEmpty() == true)
{
cout << "Empty~!!" << endl;
}
else
{
return stack[top--];
}
}
void Stack::print() //자료 구조 안의 내용을 전부 출력하기
{
for (int i = 0; i < top + 1; i++)
{
cout << stack[i] << endl;
}
}
main.cpp :
#include<iostream>
#include "stack.cpp"
using namespace std;
int main()
{
Stack stack(5);
stack.push('a');
stack.push('b');
stack.push('c');
stack.push('d');
stack.push('e');
stack.push('f');
stack.print();
stack.pop();
stack.pop();
stack.print();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
return 0;
}
출력 결과 :
'자료 구조 및 알고리즘' 카테고리의 다른 글
자료 구조 그래프 (0) | 2023.07.25 |
---|---|
Dynamic Programming (동적 계획법) (0) | 2023.07.18 |
자료 구조 Heap와 구현하기 (C++) (0) | 2023.07.06 |
자료 구조 Dequeue와 구현하기 (C++) (0) | 2023.07.02 |
자료 구조 Queue와 구현하기 (C++) (0) | 2023.07.02 |