链式栈

作者: qianranow | 来源:发表于2021-03-27 08:02 被阅读0次

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct Node {
        int data;
        struct Node *next;
    } LNode, *LinkStack;
    
    LinkStack InitStack() {
        return NULL;
    }
    
    int Push(LinkStack *s, int e) {
        LNode *p = (LNode *)malloc(sizeof(LNode));
        if (p == NULL) return -1;
        p->next = *s;
        *s = p;
        p->data = e;
        return 1;
    }
    
    int Pop(LinkStack *s, int *e) {
        if (*s == NULL) return -1;
        LNode *p = (*s)->next;
        *e = (*s)->data;
        free(*s);
        *s = p;
        return 1;
    }
    
    int GetTop(LinkStack s, int *e) {
        if (s == NULL) return -1;
        *e = s->data;
        return 1;
    }
    
    void PrintfStack(LinkStack s) {
        LNode *p = s;
        while (p != NULL) {
            printf("%i\n", p->data);
            p = p->next;
        }
    }
    
    void Sep() {
        printf("**************\n");
    }
    
    int main() {
        LinkStack s = InitStack();
        Push(&s, 123);
        Push(&s, 13);
        Push(&s, 12);
        Push(&s, 11);
        Push(&s, 119);
        PrintfStack(s);
        Sep();
        int e = -1;
        Pop(&s, &e);
        Pop(&s, &e);
        printf("%i\n", e);
        Sep();
        PrintfStack(s);
        Sep();
        GetTop(s, &e);
        printf("%i\n", e);
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:链式栈

          本文链接:https://www.haomeiwen.com/subject/ivulhltx.html