数据结构day7

链栈的实现

头文件

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值