栈的链式表示和实现

1、

//
//  main.c
//  001-栈的链式表示和实现
//

#include <stdio.h>
#include <stdlib.h>

typedef char SElemType;

typedef struct SqStack{
    SElemType data;
    struct SqStack * next;
}SqStack, *SqStackNode;

typedef struct {
    SqStack * top;
    SqStack * base;
}SqStackLink;


int initSqStack(SqStackLink * s){
    SqStackNode p = (SqStackNode)malloc(sizeof(SqStack));
    if (!p) {
        printf("分配失败\n");
        return 0;
    }
    p->next = NULL;
    s->top = p;
    s->base = s->top;
    return 1;
}

int push(SqStackLink * s, SElemType elem){
    SqStackNode p = (SqStackNode)malloc(sizeof(SqStack));
    if (!p) {
        printf("分配失败\n");
        return 0;
    }
    p->next = s->top;
    s->top->data = elem;
    s->top = p;
    return 1;
}
int pop(SqStackLink * s, SElemType * elem) {
    if (s->top == s->base) {
        printf("这是空栈\n");
        return 0;
    }
    SqStackNode p = s->top->next;
    s->top->next = p->next;
    *elem = p->data;
    free(p);
    return 1;
}




int main(int argc, const char * argv[]) {
    // insert code here...
//    printf("Hello, World!\n");
    
    SqStackLink s;
    initSqStack(&s);
    
    for (int i = 0; i < 5; i++) {
        push(&s, 'A' + i);
    }
    
    for (int i = 0; i < 2; i++) {
        SElemType elem;
        pop(&s, &elem);
        printf("pop elem is %c\n", elem);
    }
    
    return 0;
}
输出结果:

pop elem is E
pop elem is D
Program ended with exit code: 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值