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

}

运行结果:

相关推荐
思捻如枫7 小时前
C++数据结构和算法代码模板总结——算法部分
数据结构·c++
小猫咪怎么会有坏心思呢7 小时前
华为OD机考 - 水仙花数 Ⅰ(2025B卷 100分)
数据结构·链表·华为od
hn小菜鸡8 小时前
LeetCode 1356.根据数字二进制下1的数目排序
数据结构·算法·leetcode
SuperCandyXu11 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
lyh134412 小时前
【SpringBoot自动化部署方法】
数据结构
MSTcheng.12 小时前
【数据结构】顺序表和链表详解(下)
数据结构·链表
慢半拍iii13 小时前
数据结构——F/图
c语言·开发语言·数据结构·c++
iceslime13 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析
witton15 小时前
美化显示LLDB调试的数据结构
数据结构·python·lldb·美化·debugger·mupdf·pretty printer
chao_78916 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表