[数据结构]顺序栈

#include 
#include 
#define MAXSIZE 20

typedef struct Stack {
    int data[MAXSIZE];
    int top;

}Stack;

Stack* Init_Stack(Stack*, int); 
void pushStack(Stack*, int); 
void Print_Stack(Stack*); 
int popStack(Stack* ptr, int temp);

int main() {    
    Stack* ptr = NULL; int temp = 0;
    ptr = Init_Stack(ptr, MAXSIZE);

    for (int i = 0; i < 20; i++) {
        pushStack(ptr, 10 * i + 10);
    }

    Print_Stack(ptr);
    printf("current top=%d\n", ptr->top); 
    printf("弹出的数据:%d\n",popStack(ptr,temp));
    printf("current top=%d\n", ptr->top); 
    Print_Stack(ptr);
    return 0;
}

Stack* Init_Stack(Stack* ptr, int maxsize) 
{
    ptr = (Stack*)malloc(maxsize * sizeof(Stack));
    ptr->top = -1;
    return ptr;
}

void pushStack(Stack* ptr, int value) 
{
    if ((ptr->top) == MAXSIZE-1) {
        printf("已经满栈了\n");
        return;
    }
    else if (ptr->top == -1) {
        ptr->top++;ptr->data[ptr->top] = value; 
    }
    else {
        ptr->top++;ptr->data[(ptr->top) ] = value; 
    }
}

void Print_Stack(Stack* ptr) 
{
    for (int i = 0; i < MAXSIZE; i++) {

        printf("%d\n", ptr->data[i]);
    }
}

int popStack(Stack* ptr,int temp)
{ 
    printf("current top=%d", ptr->top);
    if (ptr->top == -1){ 
        printf("空栈"); 
        return; 
        }
    else{
        return ptr->data[ptr->top--];
    }
}

你可能感兴趣的:(数据结构)