数据结构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;

}

运行结果:

相关推荐
小指纹1 小时前
图论-最短路Dijkstra算法
数据结构·c++·算法·深度优先·图论
再卷也是菜4 小时前
数据结构(12)二叉树
数据结构
qq_513970444 小时前
力扣 hot100 Day63
数据结构·算法·leetcode
lifallen4 小时前
AbstractExecutorService:Java并发核心模板解析
java·开发语言·数据结构·算法
神器阿龙5 小时前
排序算法-归并排序
数据结构·算法·排序算法
爱吃KFC的大肥羊7 小时前
C/C++常用字符串函数
c语言·数据结构·c++·算法
武文斌777 小时前
嵌入式——数据结构:基础知识和链表①
数据结构
神器阿龙9 小时前
排序算法-冒泡排序
数据结构·算法·排序算法
九章数学体系10 小时前
九章数学体系:打破“吃苦悖论”,重构学习真谛
数据结构·学习·算法·数学建模·拓扑学
一川月白70910 小时前
数据结构---概念、数据与数据之间的关系(逻辑结构、物理结构)、基本功能、数据结构内容、单向链表(该奶奶、对象、应用)
c语言·数据结构·算法·哈希算法·单向链表·数据关系