1. 程式人生 > >stack的陣列實現(結構體封裝版)

stack的陣列實現(結構體封裝版)

//棧的陣列實現(結構體封裝版)
//-->棧被定義為結構體指標,具體陣列也被定義為指標,棧動態新建
#define MAXSIZE 100
struct node
{
    int capacity;//棧容量
    int top;//棧頂
    int* array;//陣列存具體棧元素
};
void Push(struct node* stack,int element)
{
    if(stack->top==MAXSIZE-1){
        printf("The stack is full!\n");
        return;
    }
    stack->array[++stack->top]=element;

}
void Pop(struct node* stack)
{
    if(stack->top!=-1)
       stack->top--;
}
void Top(struct node* stack)
{
    if(stack->top!=-1)
        printf("%d\n",stack->array[stack->top]);
    else
        printf("Empty stack!\n");
}
void PopandTop(struct node* stack)
{
    if(stack->top!=-1)
        printf("%d\n",stack->array[stack->top--]);
    else
        printf("Empty stack!\n");
}
int main()
{
    //棧的新建
    struct node* stack;
    stack=(struct node* )malloc(sizeof(struct node));
    //棧初始化(棧的array陣列分配空間,但不用初始化)
    stack->capacity=MAXSIZE;
    stack->top=-1;//top初始化為-1
    stack->array=(int *)malloc(sizeof(int)*MAXSIZE);
    //Push
    Push(stack,10);
    //Pop
    Pop(stack);
    //Top
    Top(stack);
    //PopandTop
    PopandTop(stack);

    return 0;
}