1.栈类型
2.链式栈
3.实例
cpp
#ifndef LINKSTACK_H
#define LINKSTACK_H
typedef struct{
char name[32];
char sex;
int age;
int score;
}DATATYPE;
typedef struct LinkStackNode {
DATATYPE data;
struct LinkStackNode *next;
}LinkStackNode;
typedef struct{
LinkStackNode *top;// head
int clen;
}LinkStackList;
LinkStackList* CreateLinkStackList();
int DestroyLinkStack(LinkStackList*ls);
int PushLinkStack(LinkStackList*ls,DATATYPE* data);
int PopLinkStack(LinkStackList*ls);
int GetSizeLinkStack(LinkStackList*ls);
DATATYPE*GetTopLinkStack(LinkStackList*ls);
int IsEmptyLinkStack(LinkStackList*ls);
#endif // LINKSTACK_H
cpp
#include "linkstack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
LinkStackList *CreateLinkStackList()
{
LinkStackList *ls=(LinkStackList*)malloc(sizeof(LinkStackList));
if(NULL == ls)
{
perror("CreateLinkStackList malloc");
return NULL;
}
ls->top =NULL;
ls->clen = 0 ;
return ls;
}
int PushLinkStack(LinkStackList *ls, DATATYPE *data)
{
LinkStackNode* newnode = malloc(sizeof(LinkStackNode));
if(NULL == newnode)
{
perror("PushLinkStack malloc");
return 1;
}
memcpy(&newnode->data,data,sizeof(DATATYPE));
newnode->next = NULL;
if(IsEmptyLinkStack(ls))
{
ls->top = newnode;
}
else
{
newnode->next = ls->top;
ls->top = newnode;
}
ls->clen++;
return 0;
}
int PopLinkStack(LinkStackList *ls)
{
if(IsEmptyLinkStack(ls))
{
return 1;
}
LinkStackNode* tmp = ls->top;
ls->top = ls->top->next;
free(tmp);
ls->clen--;
return 0 ;
}
int IsEmptyLinkStack(LinkStackList *ls)
{
return 0 == ls->clen;
}
int GetSizeLinkStack(LinkStackList *ls)
{
return ls->clen;
}
DATATYPE *GetTopLinkStack(LinkStackList *ls)
{
if(IsEmptyLinkStack(ls))
return NULL;
return &ls->top->data;
}
int DestroyLinkStack(LinkStackList *ls)
{
int len = GetSizeLinkStack(ls);
int i = 0 ;
for(i = 0 ;i<len;i++)
{
PopLinkStack(ls);
}
free(ls);
return 0;
}
(ls->top = ls->top->next 时中间的tmp 则可被释放 // )
cpp
#include <stdio.h>
#include "linkstack.h"
int main()
{
LinkStackList *ls = CreateLinkStackList();
DATATYPE data[5]={
{"zhangsan",'m',20,70},
{"lisi",'f',21,60},
{"wangmazi",'m',25,80},
{"liubei",'f',30,85},
{"caocao",'f',40,90},
};
int i = 0 ;
for(i = 0 ;i<5;i++)
{
PushLinkStack(ls,&data[i]);
}
int size = GetSizeLinkStack(ls);
DATATYPE* tmp;
for(i=0;i<size;i++)
{
tmp = GetTopLinkStack(ls);
printf("name:%s score:%d\n",tmp->name,tmp->score);
PopLinkStack(ls);
}
DestroyLinkStack(ls);
printf("Hello World!\n");
return 0;
}