C++ 예제 (Stack 자료구조)

개요

안녕하세요.

C++ 자료구조 (Data Structure)의 가장 기본인 Stack 을 구현한 예제입니다.

  • 마지막에 들어간 값이 먼저 나오는 LIFO (Last In First Out) 구조.
  • 배열 (Array) 로 구성

  • Push, Pop 이 일어날 때 배열의 값이동(X), 인덱스 (top) 이동(O)
  • 생성자에서 동적할당하는 클래스는 복사생성자, 대입연산자를 따로 정의
    (Queue 예제를 참조하여 Do it yourself. 아래 예제에서 생략)


개발 환경

  • C++17, Qt Creator 9.0.1, MinGW 11.2.0 64bit
  • Windows 11 Pro

 

stack.h

#ifndef STACK_H
#define STACK_H

const int MAX = 5;

class Stack
{
public:
    Stack(int _size=MAX);
    ~Stack();

public:
    void push(int v);
    int pop();
    void print();
    inline int length() {return size;}

private:
    bool isFull();
    bool isEmpty();

private:
    int top, size;
    int *p;
};

#endif // STACK_H


stack.cpp

#include "stack.h"
#include <iostream>
#include <cstring>
using namespace std;

Stack::Stack(int _size)  : top(0), size(_size), p(nullptr)
{
    cout << "Contructor" << '\n';
    p = new int[size];
    memset(p, 0, sizeof(int)*size);
}

Stack::~Stack()
{
    cout << "Destructor" << '\n';
    if(p)
    {
        delete[] p;
        p = nullptr;
    }
}

void Stack::print()
{
    for(int i=0; i<size; i++)
    {
        cout << p[i] << ' ';
    }
    cout << '\n';
}

void Stack::push(int v)
{
    if (!isFull())
        p[top++] = v;
    else
        cout << "Stack is full" << '\n';
}

int Stack::pop()
{
    if (isEmpty())
    {
        cout << "Stack is empty" << '\n';
        return -1;
    }

    return p[--top];
}

bool Stack::isFull()
{
    return (top>=size) ? true : false;
}

bool Stack::isEmpty()
{
    return (top<=0) ? true : false;
}


main.cpp

#include <iostream>
#include "stack.h"

using namespace std;

int main()
{    
    Stack s;

    // push
    for(int i=0; i<5; i++)
        s.push(i);

    s.print();

    // pop
    for(int i=0; i<5; i++)
        cout << s.pop() << ' ';
    cout << '\n';

    return 0;
}


output

감사합니다.

댓글

이 블로그의 인기 게시물

Qt Designer 설치하기

C++ 예제 (소켓 서버, 이미지, 파일전송)