天天看點

(四)順序棧的入棧和出棧

棧的基本思想是先進後出,如同彈夾的子彈壓入和彈出,一般叫進棧和出棧。

順序棧的結構定義

typedef int SElemType;
typedef struct {
    SElemType data[MAXSIZE];
    int top;
}SqStack;
           

初始化、入棧和出棧函數

//初始化
Status InitStack(SqStack *s){
    s->top = -1;
    return OK;
};

//插入元素e為新的棧頂元素
Status Push(SqStack *s,SElemType e){
    if(s->top == MAXSIZE-1)
        return ERROR;
    s->top++;
    s->data[s->top] = e;
    return OK;
}

//出棧
Status Pop(SqStack *s,SElemType *e){
    if(s->top == -1){
        return ERROR;
    }
    *e = s->data[s->top];
    s->top--;
    return OK;
}

Status OutputStack(SqStack s){
    int i;
    for (i = 0; i <= s.top; i++) {
        printf("第%d個元素值是%d\n",i+1,s.data[i]);
    }
}
           

main函數

int main() {
    SqStack s;
    InitStack(&s);

    int x;
    SElemType e;
    printf("請輸入要入棧幾個元素:");
    scanf("%d",&x);
    for (int i = 0; i < x; i++) {
        printf("請輸入要入棧的元素的值:");
        scanf("%d",&e);
        Push(&s,e);
    }

    OutputStack(s);

    Pop(&s,&e);
    printf("出棧數:%d",e);
    return 0;
}