数据结构——链式栈

采用链式存储的方式构建栈

#include<bits/stdc++.h>

using namespace std;

#define ElementType int

typedef struct LinkNode{
    ElementType data;
    struct LinkNode *next;
} *LiStack;

bool InitStack(LiStack &S){
    S = (LinkNode *)malloc(sizeof(LinkNode));
    if(S == NULL){
        printf("Init Stack Failed!\n");
        return false;
    }
    S->next = NULL;
    return true;
}

bool Push(LiStack &S,ElementType x){
    LinkNode *p = S;
    while(p->next!=NULL){
        p=p->next;
    }
    p->next = (LinkNode *)malloc(sizeof(LinkNode));
    if(p->next == NULL){
        printf("Push Failed!\n");
        return false;
    }
    p->next->data = x;
    p->next->next = NULL;
    return true;
}
bool IsEmpty(LiStack &S){
    return S->next == NULL;
}

bool Pop(LiStack &S){
    if(IsEmpty(S)){
        printf("Stack is Empty");
        return false;
    }
    LinkNode *p=S;
    while(p->next->next!=NULL){
        p = p->next;
    }
    free(p->next);
    p->next = NULL;
    return true;
}

bool GetTop(LiStack &S,ElementType &x){
    if(IsEmpty(S)){
        printf("Stack is Empty");
        return false;
    }
    LinkNode *p = S;
    while(p->next!=NULL){
        p=p->next;
    }
    x = p->data;
    return true;
}

bool print(LiStack &S){
    if(IsEmpty(S)){
        printf("Stack is Empty");
        return false;
    }
    LinkNode *p = S;
    while(p->next!=NULL){ 
        p = p->next;
        printf("%d\n",p->data);
       
    }
    return true;
    
}

void test(){
    LiStack S;
    InitStack(S);
    Push(S,1);
    Push(S,2);
    Push(S,3);
    Push(S,4);
    Pop(S);
    int x;
    GetTop(S,x);
    print(S);
    printf("取出一个数据为:%d",x);
}

int main()
{
    test();
    return 0;
}
posted @ 2024-01-24 15:52  想成为编程高手的阿曼  阅读(7)  评论(0编辑  收藏  举报