본문 바로가기
IT/[Everyday]Coding

C++로 간단하게 구현한 스택

by Jang HyunWoong 2014. 12. 19.

  1. #include <cstdlib>
  2. #include <iostream>
  3. using namespace std;
  4. class stack
  5. {
  6. private:
  7. int nArray[10];
  8. int top;
  9. public:
  10. stack();
  11. void push(int data);
  12. int pop();
  13. void print();
  14. };
  15. stack::stack()
  16. {
  17. top = -1;
  18. }
  19. void stack::push(int data)
  20. {
  21. if(top == 9)
  22. {
  23. cout << "더이상 들어갈곳이 없습니다!" << endl;
  24. return ;
  25. }
  26. nArray[++top] = data;
  27. }
  28. int stack::pop()
  29. {
  30. if(top == -1)
  31. {
  32. cout << "스택이 비었습니다!" << endl;
  33. return 0;
  34. }
  35. return nArray[top--];
  36. }
  37. void stack::print()
  38. {
  39. int i;
  40. for(i=0; i<=top; i++)
  41. {
  42. cout << nArray[i] << " ";
  43. }cout << endl;
  44. }
  45.  
  46. int main(int argc, char *argv[])
  47. {
  48. stack s1;
  49. char getChar;
  50. int pushNum=0;
  51.  
  52. do{
  53. cout << "a)push b)pop c)print d)end" << endl;
  54. cin >> getChar;
  55.  
  56. switch(getChar)
  57. {
  58. case 'a':
  59. cout << "Push your number : ";
  60. cin >> pushNum;
  61. s1.push(pushNum);
  62. break;
  63. case 'b':
  64. s1.pop();
  65. break;
  66. case 'c':
  67. s1.print();
  68. break;
  69. case 'd':
  70. return 0;
  71. default:
  72. cout << "다시 입력하세요" << endl;
  73. }
  74. }while(~(getChar=='d'));
  75.  
  76. system("PAUSE");
  77. return EXIT_SUCCESS;
  78. }


반응형

'IT > [Everyday]Coding' 카테고리의 다른 글

배열 회전  (0) 2014.12.19
두 원소 바꾸기 swap()  (0) 2014.12.19
셀 정렬 in C#  (0) 2014.12.19
삽입정렬 in C#  (0) 2014.12.19
선택정렬 in C#  (0) 2014.12.19