数据结构day7栈-链式栈原理及实现

 

 

 全部代码:

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linkstack.h"

int main(int argc, char *argv[])
{
	linkstack s;
	s = stack_create();


	if(s == NULL)
	{
		return -1;

	}
	stack_push(s, 10);
	stack_push(s, 20);
	stack_push(s, 30);
	stack_push(s, 40);
	stack_push(s, 50);
#if 0
	while(!stack_empty(s))//栈不空,出栈
	{
		printf("pop : %d\n",stack_pop(s));
	}
	
#endif
	s = stack_free(s);

	return 0;
}

linkstack.h

typedef int data_t;

typedef struct node{
	data_t data;
	struct node *next;

}listnode, *linkstack;

linkstack stack_create();
int stack_push(linkstack s, data_t value);
data_t stack_pop(linkstack s);
int stack_empty(linkstack s);
data_t stack_top(linkstack s);
linkstack stack_free(linkstack s);

linkstack.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linkstack.h"


linkstack stack_create(){
	linkstack s;
	s = (linkstack)malloc(sizeof(listnode));
	if(s == NULL)
	{
		printf("malloc failed\n");
		return NULL;
	}
	s->data = 0;
	s->next = NULL;

}
int stack_push(linkstack s, data_t value){
	linkstack p;
	if(s == NULL)
	{
		printf("s is NULL\n");
		return -1;
	}
	p = (linkstack)malloc(sizeof(listnode));
	if(p == NULL)
	{
		printf("malloc failed\n");
		return -1;
	}

	p->data = value;
	//p->next = NULL;
	

	p->next = s->next;
	s->next = p;

	return 0;


}
data_t stack_pop(linkstack s){
	linkstack p;
	data_t t;

	p = s->next;
	s->next = p->next;

	t = p->data;

	free(p);

	p=NULL;

	return t;



}

//1-empty
int stack_empty(linkstack s){
	if(s == NULL)
	{
		printf("s is NULL\n");
		return -1;
	}

	return (s->next == NULL ? 1 : 0);

}
data_t stack_top(linkstack s){

	return (s->next->data);//栈顶的元素

}
linkstack stack_free(linkstack s){
	linkstack p;

	if(s == NULL)
	{
		printf("s is NULL\n");
		return NULL;
	}

	while(s != NULL)
	{
		p = s;
		s = s->next;
		printf("free:%d\n",p->data);
		free(p);
	}

	return NULL;

}

 运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aurora Smith

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值