//LinkStack.h
#ifndef LINKSTACK_H_
#define LINKSTACK_H_
#include <stdio.h>
typedef int ElementType;
typedef enum
{
false_,
true_
}bool_;
typedef struct StackNode
{
ElementType data;
struct StackNode *next;
}StackNode;
typedef struct LinkStack
{
int size;
StackNode *Node;
}LinkStack, *pLinkStack;
void initStack(LinkStack *st);
bool_ push(LinkStack *st, ElementType e);
bool_ pop(LinkStack *st);
void show(LinkStack st);
bool_ getTop(LinkStack st, ElementType *e);
bool_ isEmpty(LinkStack st);
int length(LinkStack st);
void destroy(LinkStack *st);
#endif //LINKSTACK_H_
#include "LinkStack.h"
#include <stdlib.h>
void initStack(LinkStack *st)
{
st->Node = NULL;
st->size = 0;
}
bool_ push(LinkStack *st, ElementType e)
{
StackNode *node = (StackNode *)malloc(sizeof(StackNode));
if( NULL == node )
{
printf("申请节点失败\n");
return false_;
}
node->data = e;
node->next = NULL;
node->next = st->Node;
st->Node = node;
st->size++;
return true_;
}
bool_ pop(LinkStack *st)
{
if( isEmpty(*st))
{
printf("栈已空\n");
return false_;
}
StackNode *p = st->Node;
st->Node = p->next;
free(p);
st->size--;
return true_;
}
void show(LinkStack st)
{
StackNode *p = st.Node;
while (NULL != p)
{
printf("%d\n", p->data);
p = p->next;
}
}
bool_ getTop(LinkStack st, ElementType *e)
{
if( isEmpty(st) )
{
printf("栈已空\n");
return false_;
}
*e = st.Node->data;
return true_;
}
bool_ isEmpty(LinkStack st)
{
return NULL == st.Node;
}
int length(LinkStack st)
{
return st.size;
}
void destroy(LinkStack *st)
{
if( NULL == st->Node ) //已pop完所有数据,由于
return ;
StackNode *p = st->Node;
while(NULL != p)
{
st->Node = p->next;
free(p);
p = st->Node;
}
st->size = 0;
}
//main.c
#include "LinkStack.h"
#include <stdlib.h>
int main()
{
LinkStack st; //指向节点的指针
ElementType e = 0;
initStack(&st);
printf("入栈操作\n");
for (int i = 0; i < 20; i++)
push(&st, i);
printf("栈大小为%d\n", length(st));
printf("显示栈中元素\n");
show(st);
getTop(st, &e);
printf("栈顶元素是%d\n", e);
printf("出栈操作\n");
for (int i = 0; i < 10; i++)
pop(&st);
printf("显示栈中元素\n");
show(st);
printf("栈大小为%d\n", length(st));
destroy(&st);
show(st);
printf("栈大小为%d\n", length(st));
system("pause");
return 1;
}