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

全部代码:

main.c

cpp 复制代码
#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

cpp 复制代码
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

cpp 复制代码
#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;

}

运行结果:

相关推荐
Croa-vo12 分钟前
TikTok 数据工程师三轮 VO 超详细面经:技术深挖 + 建模推导 + 压力测试全记录
javascript·数据结构·经验分享·算法·面试
蘑菇小白19 分钟前
时间复杂度
数据结构·算法
Cx330❀1 小时前
C++ STL set 完全指南:从基础用法到实战技巧
开发语言·数据结构·c++·算法·leetcode·面试
阿昭L2 小时前
堆结构与堆排序
数据结构·算法
.YM.Z11 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
sin_hielo15 小时前
leetcode 2435
数据结构·算法·leetcode
crescent_悦15 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
稚辉君.MCA_P8_Java18 小时前
Gemini永久会员 Java动态规划
java·数据结构·leetcode·排序算法·动态规划
cookqq18 小时前
mongodb根据索引IXSCAN 查询记录流程
数据结构·数据库·sql·mongodb·nosql
ohyeah19 小时前
栈:那个“先进后出”的小可爱,其实超好用!
前端·数据结构