链栈(c++)

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
typedef int elemtype;

typedef struct StackNode {
    elemtype data;  
    struct StackNode *next;
}StackNode;

typedef struct LinkStack {
    StackNode* top;
    int count;
}LinkStack;

void initstack(LinkStack* L) {
    L->top = NULL;
    L->count = 0;
}

int Push(LinkStack* L, elemtype e) {
    StackNode* s;
    s = (StackNode*)malloc(sizeof(StackNode));//分配动态内存
    s->data = e;
    s->next = L->top;
    L->top = s;
    L->count--;
    return 0;
}

int Pop(LinkStack* L, elemtype* e) {
    if (L->count == 0)
    {
        printf("栈为空!");
        return 0;
    }
    StackNode* s;
    s = L->top;
    L->top = s->next;
    *e = s->data;
    L->count--;
    return 0;
}

void Show_Linkstruct(LinkStack* L) {
    StackNode* s;
    s = L->top;
    if (L->count == 0)
    {
        printf("栈为空!");
    }
    else {
        while (L->top!=NULL)
        {
            printf("栈元素为:");
            printf("%d\n", L->top->data);
            L->top = L->top->next;
        }
    }
    L->top = s;
}

int main() {
    LinkStack L;
    elemtype m;
    initstack(&L);
    Push(&L, 5);
    Push(&L, 15);
    Push(&L, 25);
    Push(&L, 35);
    Push(&L, 45);
    Show_Linkstruct(&L);
    Pop(&L, &m);
    printf("删除的元素为:%d\n", m);
    Show_Linkstruct(&L);
}

 

posted @ 2022-05-30 15:09  fight挺  阅读(31)  评论(0)    收藏  举报