C语言数据结构-链式栈

发布于:2025-05-30 ⋅ 阅读:(35) ⋅ 点赞:(0)

头文件:stack.h

#ifndef __STACK_H__
#define __STACK_H__

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

typedef int DataType;

/* 链式栈节点类型 */
typedef struct staNode
{
    DataType data;
    struct staNode *pNext;
}StackNode;


/* 链式栈标签类型 */
typedef struct list
{
    StackNode *pTop;   //指向栈顶指针
    int cLen;
}StackList;

extern StackList *createSatckList();
extern int isEmptyStackList(StackList *);
extern int pushStackList(StackList *, DataType );
extern int popStackList(StackList *, DataType *);
extern DataType getStackTop(StackList *);
extern void clearStackList(StackList *);
extern void destroyStackList(StackList **);

extern void showStackList(StackList *pList);
#endif
源文件:stack.c main.c

stack.c

#include "stack.h"

StackList *createSatckList()
{
    StackList *pList = malloc(sizeof(StackList));
    if (NULL == pList)
    {
        perror("fail to malloc");
        return NULL;
    }
    pList->pTop = NULL;
    pList->cLen = 0;

    return pList;
}


int isEmptyStackList(StackList *pList)
{
    return pList->cLen == 0;
}

入栈:
int pushStackList(StackList *pList, DataType data)
{
    StackNode *pTmpNode = malloc(sizeof(StackNode));
    if (NULL == pTmpNode)
    {
        perror("fail to malloc");
        return -1;
    }
    pTmpNode->data = data;
    pTmpNode->pNext = NULL;

    pTmpNode->pNext = pList->pTop;
    pList->pTop = pTmpNode;
    pList->cLen++;

    return 0;
}

遍历:

void showStackList(StackList *pList)
{
    StackNode *pTmpNode = pList->pTop;
    while (pTmpNode != NULL)
    {
        printf("%d ", pTmpNode->data);
        pTmpNode = pTmpNode->pNext;
    }
    printf("\n");
}

出栈:
int popStackList(StackList *pList, DataType *pOutData)
{
    if (isEmptyStackList(pList))
    {
        return 0;
    }
    StackNode *pTmpNode = pList->pTop;
    if (NULL != pOutData)
    {
        *pOutData = pTmpNode->data;
    }
    pList->pTop = pTmpNode->pNext;
    free(pTmpNode);
    pList->cLen--;

    return 0;
}

DataType getStackTop(StackList *pList)
{
    if (!isEmptyStackList(pList))
    {
        return pList->pTop->data;
    }
}

void clearStackList(StackList *pList)
{
    while (pList->pTop != NULL)
    {
        popStackList(pList, NULL);
    }
}

销毁:

void destroyStackList(StackList **ppList)
{
    clearStackList(*ppList);
    free(*ppList);
    *ppList = NULL;
}
main.c

#include "stack.h"


int main(int argc, const char *argv[])
{
    StackList *pList = NULL;
    DataType OutData;

    pList = createSatckList();

    pushStackList(pList, 1);
    pushStackList(pList, 2);
    pushStackList(pList, 3);
    pushStackList(pList, 4);

    showStackList(pList);

    popStackList(pList, &OutData);
    printf("pop data = %d\n", OutData);

    showStackList(pList);

    destroyStackList(&pList);
    return 0;
}