頭文件: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;
}
?