课后习题 3.10改写 用栈逆置顺序表

SeqList.h

#pragma once
#include<iostream>
using namespace std;

class SeqList {
public:
    int* elements;
    int maxSize;
    int len;

    SeqList(int size = 30) {
        maxSize = size;
        elements = new int[maxSize];
        len = 0;
    }

    void creat(int* arr, int n) {
        if (n > 10) {
            //
        }
        for (int i = 0; i < n; i++) {
            elements[i] = arr[i];
            len++;
        }
    }

    void show() {
        for (int i = 0; i < len; i++) {
            cout << elements[i] << " ";
        }
        cout << endl;
    }

};

Stack.h

#pragma once

class Stack {
public:
    int* elements;
    int maxSize;
    int top;

    Stack(int size = 50) {
        maxSize = size;
        elements = new int[maxSize];
        top = -1;
    }

    void push(int e) {
        if (top == maxSize - 1) {
            //
        }
        else {
            elements[++top] = e;
        }
    }

    bool pop(int& e) {
        bool res = true;
        if (top == -1) {
            res = false;
        }
        else {
            e = elements[top--];
        }
        return res;
    }

};

MyTool.h

#pragma once
#include"SeqList.h"
#include"Stack.h"

class MyTool {
public:
    static void turn(SeqList& L) {
        Stack s;
        for (int i = 0; i < L.len; i++) {
            s.push(L.elements[i]);
        }
        bool bl;
        int temp;
        for (int i = 0; i < L.len; i++) {
            bl = s.pop(temp);
            if (bl == false) {
                cerr << "666" << endl;
                exit(1);
            }
            else {
                L.elements[i] = temp;
            }
        }
    }
};

main.cpp

#include"MyTool.h"

int main() {
    SeqList L;
    int arr[] = { 1,2,3,4,5 };
    L.creat(arr, 5);
    MyTool::turn(L);
    L.show();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/SlowIsFast/p/12624996.html