printf("ho_tari\n");
Stack 본문
<main.cpp>
//#include <cstdio>
#include <iostream>
#include "stack.h"
int main()
{
Stack s1(10), s2(100);
//s1.initStack(10);
//s2.initStack(100);
s1.push(100);
s1.push(200);
s1.push(300);
//s1.tos = 0;
//printf("s1 1st pop() : %d\n", s1.pop());
std::cout << "s1 1st pop() : ";
std::cout << s1.pop();
std::cout << std::endl;
//printf("s1 2nd pop() : %d\n", s1.pop());
std::cout << "s1 2nd pop() : " << s1.pop() << std::endl;
//printf("s1 3rd pop() : %d\n", s1.pop());
std::cout << "s1 3rd pop() : " << s1.pop() << std::endl;
s2.push(900);
s2.push(800);
s2.push(700);
//printf("s2 1st pop() : %d\n", s2.pop());
std::cout << "s2 1st pop() : " << s2.pop() << std::endl;
//printf("s2 2nd pop() : %d\n", s2.pop());
std::cout << "s2 2nd pop() : " << s2.pop() << std::endl;
//printf("s2 3rd pop() : %d\n", s2.pop());
std::cout << "s2 3rd pop() : " << s2.pop() << std::endl;
//s1.cleanupStack();
//s2.cleanupStack();
return 0;
}
<stack.h>
#ifndef STACK_H
#define STACK_H
class Stack {
private:
int *pArr;
int size;
int tos;
public:
//void initStack(int size); --> constructor
//void cleanupStack(); --> destructor
Stack(int size); // constructor
~Stack(); // destructor
void push(int data);
int pop();
};
#endif
<stack.cpp>
//#include <cstdio>
//#include <cstdlib>
#include <cassert>
#include "stack.h"
Stack::Stack(int size)
{
//this->pArr = (int *)malloc(sizeof(int) * size);
this->pArr = new int[size];
assert(this->pArr /*!= NULL*/);
this->size = size;
this->tos = 0;
}
Stack::~Stack()
{
//free(this->pArr);
delete [] this->pArr;
}
void Stack::push(int data)
{
assert(this->tos != this->size);
this->pArr[this->tos] = data;
++this->tos;
}
int Stack::pop()
{
assert(this->tos != 0);
--this->tos;
return this->pArr[this->tos];
}
<compile 결과>
'C++' 카테고리의 다른 글
String2 (0) | 2023.09.01 |
---|---|
Rational3 (여러연산자) (0) | 2023.08.31 |
String (0) | 2023.08.31 |
Queue (0) | 2023.08.31 |
Complex3 (여러연산자) (0) | 2023.08.31 |