3.1.2.1 顺序栈的基本操作

SeqStack.h

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

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

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

    void overflowProcess() {
        int* s;
        s = new int[maxSize * 2];
        for (int i = 0; i <= top; i++) {
            s[i] = elements[i];
        }
        maxSize *= 2;
        delete []elements;
        elements = s;
    }

    bool IsFull() {
        return top == maxSize - 1;
    }

    bool IsEmpty() {
        return top == -1;
    }

    void makeEmpty() {
        top = -1;
    }

    void push(int x) {
        if (IsFull() == true) {
            overflowProcess();
        }
        elements[++top] = x;
    }

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

    bool getTop(int& x) {
        bool res;
        if (IsEmpty() == true) {
            res = false;
        }
        else {
            x = elements[top];
            res = true;
        }
        return res;
    }

};

main.cpp

#include"SeqStack.h"

int main() {
    SeqStack s;
    int arr_1[] = { 1,2,3,4,5,6,7,8,9 };
    for (int i = 0; i < 9; i++) {
        s.push(arr_1[i]);
    }
    int arr_2[] = { 2,4,6,8,0 };
    for (int i = 0; i < 5; i++) {
        s.push(arr_2[i]);
    }
    int x;
    bool bl;
    while (s.IsEmpty() == false) {
        bl = s.pop(x);
        if (bl == false) {
            cout << "false" << endl;
        }
        else{
            cout << x << " ";
        }
    }
    cout << endl;
    cout << "--------------------------" << endl;
    int arr_3[] = { 1,2,3 };
    for (int i = 0; i < 3; i++) {
        s.push(arr_3[i]);
    }
    s.makeEmpty();
    int arr_4[] = { 5,6,7,8,9 };
    for (int i = 0; i < 5; i++) {
        s.push(arr_4[i]);
    }
    
    while (s.IsEmpty() == false) {
        bl = s.pop(x);
        if (bl == false) {
            cout << "false" << endl;
        }
        else {
            cout << x << " ";
        }
    }
    cout << endl;

    return 0;
}

 

posted @ 2020-03-25 10:25  落地就是一把98K  阅读(128)  评论(0)    收藏  举报