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

}

运行结果:

相关推荐
hnjzsyjyj16 分钟前
洛谷 B3622:枚举子集(递归实现指数型枚举)← DFS
数据结构·dfs
qiqsevenqiqiqiqi2 小时前
MT2048三连 暴力→数学推导→O (n) 优化
数据结构·c++·算法
码之气三段.2 小时前
十五届山东ccpc省赛补题(update)
数据结构·c++·算法
保持清醒5404 小时前
二叉链表实现
数据结构
paeamecium4 小时前
【PAT甲级真题】- Recover the Smallest Number (30)
数据结构·算法·pat考试·pat
玛丽莲茼蒿4 小时前
Leetcode hot100 在排序数组中查找元素的第一个和最后一个位置【中等】
数据结构·算法
寒秋花开曾相惜5 小时前
(学习笔记)4.2 逻辑设计和硬件控制语言HCL(4.2.3 字级的组合电路和HCL整数表达式)
android·网络·数据结构·笔记·学习
发疯幼稚鬼5 小时前
二叉树的广度优先遍历
c语言·数据结构·算法·宽度优先
love在水一方5 小时前
【Voxel-SLAM】Data Structures / 数据结构文档(二)
数据结构·人工智能·机器学习
Via_Neo5 小时前
乘积最大问题
数据结构·算法