链栈的实现
头文件
#ifndef _LINKSTACK_H_
#define _LINKSTACK_H_
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
typedef int datatype;
typedef struct Node
{
datatype data;
struct Node *next;
}Node;
typedef struct
{
Node *top;//栈顶结点
Node *bot;//栈底结点
}stack,*linkstackptr;
//创建栈
linkstackptr stack_creat();
//入栈
int stack_push(linkstackptr LS,datatype a);
//判空
int stack_empty(linkstackptr LS);
//出栈
int stack_pop(linkstackptr LS);
//释放
void stack_free(linkstackptr LS);
#endif
源文件
#include "linkstack.h"
//创建栈
linkstackptr stack_creat()
{
linkstackptr LS =(linkstackptr)malloc(sizeof(stack));
if(NULL == LS)
{
printf("创建失败\n");
return NULL;
}
//申请结点
LS->bot =(Node *)malloc(sizeof(Node));
if(NULL == LS->bot)
{
printf("申请失败\n");
return NULL;
}
//初始化
LS->bot->next = NULL;
LS->top = LS->bot;
LS->top->data = LS->bot->data = -1;
printf("创建成功\n");
return LS;
}
//入栈
int stack_push(linkstackptr LS,datatype a)
{
if(NULL == LS)
{
printf("入栈失败\n");
return 0;
}
Node *p = (Node *)malloc(sizeof(Node));
if(NULL == p)
{
printf("申请失败\n");
free(LS);
return 0;
}
//初始化
p->data = a;
LS->top->data = p->data;
p->next=LS->top;
LS->top=p;
printf("%d入栈成功\n",a);
return 1;
}
//判空
int stack_empty(linkstackptr LS)
{
if(NULL != LS)
{
return LS->top == LS->bot;
}
printf("链栈不合法\n");
return 0;
}
//出栈
int stack_pop(linkstackptr LS)
{
if(NULL == LS)
{
printf("出栈失败\n");
return 0;
}
if(LS->top != LS->bot)
{
printf("%d出栈成功\n",LS->top->data);
LS->top = LS->top->next;
if(LS->top == LS->bot)
{
return 1;
}
LS->top->data = LS->top->next->data;
}
if(LS->top == LS->bot)
{
printf("出栈失败\n");
}
return 1;
}
//释放
void stack_free(linkstackptr LS)
{
if(NULL == LS)
{
printf("释放失败\n");
return;
}
while(!stack_empty(LS))
{
stack_pop(LS);
}
free(LS->bot);
LS->bot = LS->top = NULL;
free(LS);
LS = NULL;
printf("释放成功\n");
}
主函数
#include "linkstack.h"
int main(int argc, const char *argv[])
{
linkstackptr LS=stack_creat();
if(NULL == LS)
{
return -1;
}
stack_push(LS,1);
stack_push(LS,2);
stack_push(LS,3);
stack_push(LS,4);
stack_push(LS,5);
stack_pop(LS);
stack_pop(LS);
stack_pop(LS);
stack_pop(LS);
stack_pop(LS);
stack_free(LS);
return 0;
}