Stack:只允许一端进行插入或删除的操作
栈顶Top
栈底Bottom

栈的链式实现方式代码展示

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

typedef struct Node
{
    int data;
    struct Node *pNext;
}NODE,*PNODE;

typedef struct Stack
{
    PNODE pTop;
    PNODE pBottom;
}STACK,*PSTACK;

void init(PSTACK);//初始化
void push(PSTACK,int);//进栈
void traverse(PSTACK);
bool pop(PSTACK,int *);//出栈
void clear(PSTACK);//清空

int main (void)
{
    STACK s;
    int val;

    init(&s);//初始化
    push(&s,1);//压栈
    push(&s,2);
    push(&s,123);
    push(&s,34);

    traverse(&s);

    if(pop(&s,&val))
    {
        printf("出栈成功,出栈元素为:%d\n",val);
    }
    else
    {
        printf("出栈失效!\n");
    }

    traverse(&s);//遍历输出

    clear(&s);
    traverse(&s);

    return 0;
}

void init(PSTACK pS)
{
    pS->pTop=(PNODE)malloc(sizeof(NODE));
    if(NULL==pS->pTop)
    {
        printf("动态内存分配失败!\n");
        exit(-1);
    }
    else
    {
        pS->pBottom=pS->pTop;
        pS->pTop->pNext=NULL;
    }
}

void push(PSTACK pS,int val)
{
    PNODE pNew=(PNODE)malloc(sizeof(NODE));
    pNew->data=val;
    pNew->pNext=pS->pTop;//注意这里只能是pTop
    pS->pTop=pNew;
    return;
}

void traverse(PSTACK pS)
{
    PNODE p=pS->pTop;
    while(p!=pS->pBottom)
    {
        printf("%d",p->data);
        p=p->pNext;
    }
    printf("\n");
    return;
}
//判空
bool empty(PSTACK pS)
{
    if(pS->pTop==pS->pBottom)
        return true;
    else
        return false;
}
//出栈
bool pop(PSTACK pS,int *pVal)
{
    if(empty(pS))
    {
        return false;
    }
    else
    {
        PNODE r=pS->pTop;
        *pVal=r->data;
        pS->pTop=r->pNext;
        free(r);
        r=NULL;
        return true;
    }
}
//清空
void clear(PSTACK pS)
{
    if(empty(pS))
    {
        return;
    }
    else
    {
        PNODE p=pS->pTop;
        PNODE q=NULL;
        while(p!=pS->pBottom)
        {
            q=p->pNext;
            free(p);
            p=q;
        }
        pS->pTop=pS->pBottom;
    }
}