順序棧的一般操作

#include <stdio.h>
//define the size of array
#define MAXSIZE 100
//define new data type: stack
struct stack{
    int data[MAXSIZE];
    int top;
};
//defint var seqStack
typedef struct stack seqStack;

//create a stack
int create_stack(seqStack* S){
    //initial the top to 0
    S->top = 0;
    printf("create stack comlete!\n");
    return 0;
}

int push_stack(seqStack* S, int element){
    //is overflow?
    if(S->top > 100)
        return -1;
    //data[top] = element, at the beginning data[0] = element
    S->data[S->top] = element;
    //top + 1, point to a new empty position
    S->top++;
    printf("push %d into stack comlete!\n", element);
    return 0;
}

//print every element of the stack
int show_stack(seqStack S){
    int i;
    //top point to the new empty position, so use top-1
    for(i=(S.top-1); i>=0; i--){
        printf("%d\n",S.data[i]);
    }
    printf("show stack from top to bottom comlete!\n");
    return 0;
}


//print the top element and top-1
int pop_stack(seqStack* S){
    //is stack empty
    if (S->top == 0) {
        printf("the stack is empty!\n");
        return 0;
    }
    //good: --(S->top) will modify the value of top directly
    printf("%d\n", S->data[--(S->top)]);
    printf("pop stack from top complete!\n");
    return 0;
}


int main(){
    seqStack S;
    //create stack by seqstack address
    create_stack(&S);
    //push 15 into stack
    push_stack(&S, 15);
    //push 27 into stack
    push_stack(&S, 27);
    //push 89 into stack
    push_stack(&S, 89);
    //print stack from top to bottom
    show_stack(S);
    //return 89
    pop_stack(&S);
    //return 27
    pop_stack(&S);
    //return 15
    pop_stack(&S);
    //stack already empty, so return
    pop_stack(&S);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章