배열을 이용한 스택 구현

2022. 4. 22. 12:15C++/자료구조

2022.04.22 - [C++/자료구조] - 스택(stack) - 2

 

배열을 이용한 스택 구현

스택에서 PUSH와 POP 연산은 탑에서 일어난다. 

 

그림은 배열에서의 PUSH와 POP연산을 그림으로 표현한 것이다. 

 

 

코드 구현

//array stack.h
#define ARRAY_SIZE 100

typedef int element; //int형 자료형에 element라 별칭 붙임.

class ArrayStack
{
public:
    ArrayStack();
    ~ArrayStack();

    void Push(element item);    //item값을 스택에 삽입
    int Pop();                  //스택 탑의 데이터 값을 리턴함
    bool IsEmpty(); //비어 있는지 확인
    bool IsFull();  //꽉차 있는지 확인

private:
    int top;
    int Stack[ARRAY_SIZE];
};

 

//array stack.cpp
#include <iostream>
#include "array stack.h"

using namespace std;

ArrayStack::ArrayStack() :top(-1){}

ArrayStack::~ArrayStack(){}

void ArrayStack::Push(element item)
{
    top++; 
    Stack[top] = item;
}

int ArrayStack::Pop()
{
    if(IsEmpty())
        cout<<"빈스택입니다."<<endl;
    else
    {
        int temp = Stack[top];  //top 데이터 저장
        Stack[top] = 0;         //top값 pop
        top--;  
        return temp;    // 이전 top값 반환
    }
    
}

bool ArrayStack::IsEmpty()
{
    return bool(top == 0);
}

bool ArrayStack::IsFull()
{
    return !IsEmpty;
}

'C++ > 자료구조' 카테고리의 다른 글

스택 응용 2. 후위 표현의 연산  (0) 2022.04.23
스택 응용 1. 백 스페이스 키  (0) 2022.04.22
연결 리스트를 이용한 스택 구현  (0) 2022.04.22
스택(stack) - 2  (0) 2022.04.22
스택(stack)-1  (0) 2022.04.18