数据结构day7

头文件

#ifndef _LINKSTACK_H_
#define _LINKSTACK_H_
typedef int datatype;
typedef struct Node
{
	union
	{
		datatype data;
		int len;
	};
	struct Node * next;
}Node;
typedef struct 
{
	Node * top;
}linkstack,*linkstackptr;
//链式栈的创建
linkstackptr stack_create();
//判空
int stack_empty(linkstackptr L);
//入栈
int stack_posh(linkstackptr L,datatype e);
//出栈
int stack_pop(linkstackptr L);
//遍历栈
void stack_show(linkstackptr L);
//释放栈
void stack_free(linkstackptr L);
#endif
ubuntu@ubuntu:linkstack$ 

源文件

#include"linkstack.h"
#include<stdio.h>
#include<stdlib.h>
//链式栈的创建
linkstackptr stack_create()
{
	linkstackptr L=(linkstackptr)malloc(sizeof(linkstack));
	if(NULL==L)
	{
		printf("申请失败\n");
		return NULL;
	}
	L->top=(Node *)malloc(sizeof(Node));
	if(NULL==L->top)
	{
		printf("申请失败\n");
		free(L);
		return NULL;
	}
	L->top->len=0;
	L->top->next=NULL;
	printf("创建成功\n");
	return L;
}
//判空
int stack_empty(linkstackptr L)
{
	if(NULL==L ||NULL==L->top)
	{
		printf("所给链表不合法\n");
		return -1;
	}
	return L->top->next==NULL;
}
//入栈
int stack_posh(linkstackptr L,datatype e)
{
	if(NULL==L)
	{
		printf("所给栈不合法\n");
		return 0;
	}
	Node *p=(Node *)malloc(sizeof(Node));
	if(NULL==p)
	{
		printf("入栈失败\n");
		return 0;
	}
	p->data=e;
	p->next=L->top->next;
	L->top->next=p;
	L->top->len++;
	printf("入栈成功\n");
	return 1;
}
//出栈
int stack_pop(linkstackptr L)
{
	if(NULL==L || stack_empty(L))
	{
		printf("出栈失败\n");
		return 0;
	}
	Node *p=L->top->next;
	L->top->next=p->next;
	printf("%d出栈成功\n",p->data);
	free(p);
	p=NULL;
	L->top->len--;
	return 1;
}
//遍历栈
void stack_show(linkstackptr L)
{
	if(NULL==L)
	{
		printf("遍历失败\n");
		return ;
	}
	Node * p=L->top->next;
	while(p->next!=NULL)
	{
		printf("%d\t",p->data);
		p=p->next;
	}
	printf("%d\n",p->data);
}
//释放栈
void stack_free(linkstackptr L)
{
	if(NULL==L )
	{
		printf("释放失败\n");
		return;
	}
	while(L->top->len=0)
	{
		stack_pop(L);
	}
	free(L->top);
	L->top=NULL;
	free(L);
	L=NULL;
	printf("销毁成功\n");
}

测试文件

int main(int argc, const char *argv[])
{
    linkstackptr L=stack_create();
	if(NULL==L)
	{
		return -1;
	}
	stack_posh(L,1);
	stack_posh(L,2);
	stack_posh(L,3);
	stack_posh(L,4);
	stack_posh(L,5);
	stack_show(L);
	stack_pop(L);
	stack_show(L);
	stack_free(L);
	return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值