0
点赞
收藏
分享

微信扫一扫

c++实现顺序栈

小云晓云 2022-03-13 阅读 65
c++
#include <iostream>
#include <cstdlib>
#include <string>
#define StackInitSize 5
#define StackIncreace 2
using namespace std;

bool em(struct Stack *);
struct Stack{
    int Stack_size; //目前栈的容量
    int Stack_num;
    //定义两个指针,top指向栈顶,base指向栈底
    int *top;
    int *base;
};
void InitStack(struct Stack *stack){
    stack->base = new int[StackInitSize];
    if(stack->base == nullptr){
        cout << "memory allocation false!" << endl;
        exit(-1);
    }else{
        stack->top = stack->base;
        stack->Stack_size = StackInitSize;
        stack->Stack_num = 0;
        return;
    }
}
bool push(struct Stack *stack, int val){
    *stack->top = val;
    (stack->top)++;
    return true;
}
bool Stack_Add(struct Stack *stack, struct Stack *temp, int val){
    temp->base = new int[stack->Stack_size + StackIncreace];
    if (temp->base == nullptr){
        cout << "memory allocation false!" << endl;
        return false;
    }else{
        temp->top = temp->base;
        stack->Stack_size += StackIncreace;
        for (int i =0; i < stack->Stack_num - 1; i++){
            temp->base[i] = stack->base[i];
            ++(temp->top);
        }
        *temp->top = val;
        (temp->top)++;
        delete [] stack->base;
        stack->base = temp->base;
        stack->top = temp->top;
        return true;
    }
}
void Pop(struct Stack *stack,int &val){
    if (em(stack)){
        cout << "stack is empty" << endl;
    }else{
        val = *stack->top;
    }
    return;
}
bool em(struct Stack *stack){
    if (stack->base == stack->top){
        return true;
    }else{
        return false;
    }
}
void ShowStack(struct Stack *stack){
    for (int i = 0; i != stack->Stack_num; i++){
        cout << stack->base[i] << ",";
    }
    cout << endl;
    return;
}
int main(){
    int val,option;
    Stack stack;
    InitStack(&stack);
    Stack temp;
    cout << "Please,input a num for stack(use whitesapce separated): " << endl;
    while(cin.peek() != '\n'){
        cin >> val;
        ++stack.Stack_num;
        if (stack.Stack_num <= stack.Stack_size){
            push(&stack,val);
        }else{
            Stack_Add(&stack, &temp, val);
        }
    }

    system("pause");
    return 0;
}
举报

相关推荐

0 条评论