数据结构——链式栈

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

#include

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;
}

本文由博客一文多发平台 OpenWrite 发布!

你可能感兴趣的:(数据结构,栈)