๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๋ฌธ์ œํ’€์ด๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป

[c++] stack class๋ฅผ ๊ตฌํ˜„ํ•˜์—ฌ ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—100๋ณด๋‹ค ํฐ ๊ฐ’ ์—ญ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๊ธฐ

by hyerong 2023. 9. 24.

๋ฌธ์ œ

์ •์ˆ˜ ์›์†Œ๋ฅผ ์ €์žฅํ•˜๋Š” stack์„ class๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•˜๊ณ , ์ด๋ฅผ ์ด์šฉํ•˜์—ฌ, ์ฃผ์–ด์ง„  array์˜ ์ •์ˆ˜ ์›์†Œ n๊ฐœ ์—์„œ 100๋ณด๋‹ค

ํฐ ๊ฐ’์„ ์—ญ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. (๋‹ค์Œ main() ํ•จ์ˆ˜๊ฐ€ ๋™์ž‘ํ•˜๋„๋ก ๋‚˜๋จธ์ง€ ๋ถ€๋ถ„์„ ์ž‘์„ฑ)


int main()

{

mystack  s1;

int list[5] = { 32, 123, 27, 131, 242 }, i, x;

  s1.init();

  for (i = 0; i < 5; i++ )

         if (list[i]> 100)

                s1.push( list[i] );

  while ( ! s1.stack_empty( ) )

  {

            x = s1.pop( );

            cout << x << endl ; 

  }

  return 0;

}


๋ฌธ์ œ ํฌ์ธํŠธ 

1) ์กฐ๊ฑด์— ๋งž๊ฒŒ ์Šคํƒ์— ํ‘ธ์‹œ๋ฅผ ํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€ 

2) ์กฐ๊ฑด์— ๋งž๊ฒŒ ์Šคํƒ์—์„œ ํŒ์„ ํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€ 

3) stack class๋ฅผ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€

4) stack์˜ adt๋ฅผ ์ดํ•ดํ•˜๋Š”๊ฐ€ 



#include <iostream>
#define SIZE 100
using namespace std;

// ์ •์ˆ˜ ์›์†Œ๋ฅผ ์ €์žฅํ•˜๋Š” mystack ์ด๋ผ๋Š” class ์ƒ์„ฑ
class mystack{
int arr[SIZE];
int top;

public:
void init();
void push(int num); // ์ •์ˆ˜ํ˜• ํƒ€์ž…์˜ ๋ฐฐ์—ด์„ ๊ฐ–๋Š” push
int pop();
bool stack_empty();
};

// class ๋‚ด์˜ ๋ฉค๋ฒ„ ํ•จ์ˆ˜ ์ž‘์„ฑ
void mystack::init() {
top = 0;
}

void mystack::push(int num) {
// ํ•จ์ˆ˜ ์ดˆ๊ธฐํ™”
arr[top] = num; // top ์— ๊ฐ’ ๋„ฃ์–ด์ฃผ๊ธฐ
top++;
}

int mystack::pop() {

top--;
//int num = arr[top];
return arr[top];
}

bool mystack::stack_empty() {
// ํ•จ์ˆ˜ ์ดˆ๊ธฐํ™”
if(top == 0) return true;
else return false;
}


int main() {
//mystack์ด๋ผ๋Š” object ์ƒ์„ฑ, ๋ณ€์ˆ˜ ์ด๋ฆ„์„ s1๋กœ ์ง€์ •
mystack s1;

int list[5] = {32, 123, 27, 131, 242}, i, x;

s1.init();

for (i = 0; i < 5; i++ ) {
if (list[i]> 100) {
s1.push(list[i]);
}
}
 
while (! s1.stack_empty()) {
x = s1.pop();
cout << x << endl ;
}

return 0;

}