LinkStack.h
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>
typedef int ElemType;
//链栈
typedef struct LinkStackNode
{
struct LinkStackNode* link;
ElemType data;
}LinkStackNode;
void LinkStackInit(LinkStackNode** ppst);
void LinkStackPush(LinkStackNode** ppst,ElemType x);
void LinkStackPop(LinkStackNode** ppst);
void LinkStackShow(LinkStackNode* pst);
ElemType LinkStackTop(LinkStackNode* pst);
.
.
.
.
LinkStack.c
#include"ListStack.h"
void LinkStackInit(LinkStackNode** ppst)
{
assert(*ppst);//等价于if(*ppst)!=NULL 则进行下面的操作
*ppst = NULL;
}
void LinkStackPush(LinkStackNode** ppst, ElemType x)
{
//assert(*ppst != NULL);
LinkStackNode* newNode = (LinkStackNode*)malloc
(sizeof(LinkStackNode));
assert(newNode);
//头插
newNode->link = *ppst;
newNode->data = x;
*ppst = newNode;
}
void LinkStackPop(LinkStackNode** ppst)
{
assert(*ppst);
//没有结点
if (*ppst != NULL)
{
LinkStackNode* p = *ppst;
*ppst = p->link;
free(p);
}
}
ElemType LinkStackTop(LinkStackNode* pst)
{
assert(pst);
return pst->data;
}
void LinkStackShow(LinkStackNode* pst)
{
assert(pst);
LinkStackNode* p = pst;
while (p)
{
printf(" | %d |\n", p->data);
p = p->link;
}
printf(" ----- \n");
}
.
.
.
.
test.c
#include"ListStack.h"
void TestListStack()
{
LinkStackNode* pst=NULL;
LinkStackInit(&pst);
LinkStackPush(&pst, 1);
LinkStackPush(&pst, 2);
LinkStackPush(&pst, 3);
LinkStackPush(&pst, 4);
LinkStackPush(&pst, 5);
LinkStackShow(pst);
LinkStackPop(&pst);
LinkStackPop(&pst);
LinkStackShow(pst);
printf("top=%d", LinkStackTop(pst));
}
int main()
{
TestListStack();
return 0;
}