栈的链式表示和实现

来源:互联网 发布:java https请求带证书 编辑:程序博客网 时间:2024/05/29 03:19

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 Epop elem is DProgram ended with exit code: 0


0 0