C++ HW12-1 for WallPower
請利用堆疊特性,寫出一程式,在使用者輸入一字串後,能反轉並輸出此字串。
參考結果如下。
參考結果如下。
- #include <iostream>
- #include <stdlib.h>
- #include <string>
- using namespace std;
- #define NUM 100
- class stack {
- public:
- stack();
- void push(char);
- char pop();
- void printStack();
- private:
- char array[NUM];
- char top;
- };
- stack::stack() {
- top = -1;
- }
- void stack::push(char n)
- {
- if (top == NUM - 1) {
- cout << "stack is full!";
- exit(1);
- }
- array[++top] = n;
- }
- char stack::pop()
- {
- if (top == -1) {
- cout << "stack is empty!!";
- exit(1);
- }
- return array[top--];
- }
- void stack::printStack()
- {
- int i;
- if (top == -1) {
- cout << "stack is empty!!\n";
- }
- else {
- for (i = top; i >= 0; i--)
- cout << pop();
- cout << endl;
- }
- }
- int main(void)
- {
- int choice = 0;
- string n;
- stack S1;
- while (true)
- {
- cin >> n;
- for (int i = 0; i < n.length(); i++)
- S1.push(n[i]);
- S1.printStack();
- }
- system("pause");
- return 0;
- }
留言
張貼留言