C++ HW12-1 for WallPower

請利用堆疊特性,寫出一程式,在使用者輸入一字串後,能反轉並輸出此字串。
參考結果如下。

  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <string>
  4. using namespace std;
  5. #define NUM 100
  6.  
  7. class stack {
  8. public:
  9. stack();
  10. void push(char);
  11. char pop();
  12. void printStack();
  13. private:
  14. char array[NUM];
  15. char top;
  16. };
  17.  
  18. stack::stack() {
  19. top = -1;
  20. }
  21. void stack::push(char n)
  22. {
  23. if (top == NUM - 1) {
  24. cout << "stack is full!";
  25. exit(1);
  26. }
  27. array[++top] = n;
  28. }
  29. char stack::pop()
  30. {
  31. if (top == -1) {
  32. cout << "stack is empty!!";
  33. exit(1);
  34. }
  35. return array[top--];
  36. }
  37. void stack::printStack()
  38. {
  39. int i;
  40. if (top == -1) {
  41. cout << "stack is empty!!\n";
  42. }
  43. else {
  44. for (i = top; i >= 0; i--)
  45. cout << pop();
  46. cout << endl;
  47. }
  48. }
  49. int main(void)
  50. {
  51. int choice = 0;
  52. string n;
  53. stack S1;
  54. while (true)
  55. {
  56. cin >> n;
  57. for (int i = 0; i < n.length(); i++)
  58. S1.push(n[i]);
  59. S1.printStack();
  60. }
  61. system("pause");
  62. return 0;
  63. }

留言

這個網誌中的熱門文章

C# 井字遊戲