Under Graduate School/Data Structure 스택 구현하기 in C++ - 728x90 반응형 스택 구현하기 in C++ 스택이란? 스택(Stack)이란 여러 자료구조 중 하나로, 후입선출(LIFO; Last In, First Out)의 데이터 삽입 및 가져오기 방식을 지원하는 구조이다.예를 들어보면 우리가 [2, 4, 3, 7, 8]을 순서대로 스택에 삽입하지만, 데이터를 빼낼때는 [8, 7, 3, 4, 2]의 순서로 나오게 되는것이다. 아주 쉽게 설명하면, 우리가 살면서 한 번쯤은 먹어봤을 유명한 스낵인 프링글스가 그 예가 되겠다.분명 생산공장에서는 통의 제일 아랫부분에 있는 조각을 가장 먼저 넣었겠지만, 우리는 뚜껑을 열어 가장 위에 있는 조각부터 먹지않는가. 코드 소개 C++언어를 이용하여 스택을 구현해보는 프로그램이다. 코드 stack.h /* * stack.h * * Created on: 2017. 3. 29. * Author: Minsu */ #ifndef STACK_H_ #define STACK_H_ typedef int ItemType; const int MAX_STACK_SIZE = 30; // Set max stack size class Stack { int top; // element of stak's top ItemType data[MAX_STACK_SIZE]; // data store public: Stack(); // constructor ~Stack(); // destructor bool isEmpty(); bool isFull(); void push(ItemType e); // add element in stack ItemTypepop(); // delete and return 'top' ItemType peek(); // return 'top' }; #endif /* STACK_H_ */ stack.cpp /* * stack.cpp * * Created on: 2017. 3. 29. * Author: Minsu */ #include "stack.h" #include <iostream> #include <cstdlib> using namespace std; typedef int ItemType; inline void error(const char *message) // error handling { cout << message << endl; exit(1); } Stack::Stack() // constructor { top = -1; } Stack::~Stack() {} // destructor bool Stack::isEmpty() { return (top == -1); } bool Stack::isFull() { return (top == MAX_STACK_SIZE - 1); } void Stack::push(ItemType e) // add element in stack { if(isFull()) { error("Stack is full"); } else { data[++top] = e; } } ItemType Stack::pop() // delete and return 'top' { if(isEmpty()) { error("Stack is empty"); } return data[top--]; } ItemType Stack::peek() // return 'top' { if(isEmpty()) { error("Stack is empty"); } return data[top]; } 728x90 반응형 공유하기 URL 복사카카오톡 공유페이스북 공유엑스 공유 게시글 관리 구독하기Minsu Jo's Development Log 저작자표시 비영리 동일조건 Contents 스택이란? 코드소개 C++언어를이용하여스택을구현해보는프로그램이다. 코드 stack.h stack.cpp 당신이 좋아할만한 콘텐츠 연결리스트 구현하기 in C++ 2024.09.20 댓글 0 + 이전 댓글 더보기