2.26数据结构

链栈的代码

cpp 复制代码
//link_stack.h
#ifndef __LINK_STACK_H__
#define __LINK_STACK_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct link_stack
{
	int data;
	struct link_stack *next;
}link_stack,*link_p;

//栈顶指针类型
typedef struct top_t
{
	int len;
	link_p ptop;
}top_t,*top_p;

//申请栈顶指针
top_p create_top();
//申请结点的函数
link_p create_node(int data);
//入栈/压栈
void push_stack(top_p T,int data);
//判空
int empty_stack(top_p T);
//出栈/弹栈
void pop_stack(top_p T);
//遍历
void show(top_p T);
//销毁
void free_stack(top_p T);


#endif
cpp 复制代码
//link_stack.c
#include "link_stack.h"

//申请栈顶指针
top_p create_top()
{
	top_p top = (top_p)malloc(sizeof(top_t));
	if(top==NULL)
	{
		printf("空间申请失败\n");
		return NULL;
	}
	top->len = 0;
	top->ptop = NULL;  //刚申请栈指针时没有指向元素
	return top;
}
//申请结点的函数
link_p create_node(int data)
{
	link_p new = (link_p)malloc(sizeof(link_stack));
	if(new==NULL)
	{
		printf("申请空间失败\n");
		return NULL;
	}
	new->data = data;
	return new;
}
//入栈/压栈
void push_stack(top_p T,int data)
{
	if(T==NULL)
	{
		printf("入参为空\n");
		return;
	}
	link_p new = create_node(data);
	//入栈
	new->next = T->ptop;
	T->ptop = new;
	T->len++;
}
//判空
int empty_stack(top_p T)
{
	if(T==NULL)
	{
		printf("入参为空\n");
		return -1;
	}
	return T->ptop==NULL?1:0;
}

//出栈/弹栈
void pop_stack(top_p T)
{
	if(T==NULL)
	{
		printf("入参为空\n");
		return;
	}
	if(empty_stack(T))
	{
		printf("链栈为空\n");
		return;
	}
	link_p p = T->ptop;
	int pdata = p->data;
	T->ptop = p->next;
	T->len--;
	printf("出栈的元素:\n");
	printf("%d-->",pdata);
	free(p);
}
//遍历
void show(top_p T)
{

	if(T==NULL)
	{
		printf("入参为空\n");
		return;
	}
	if(empty_stack(T))
	{
		printf("栈为空\n");
		return;
	}
	link_p p = T->ptop;
	while (p != NULL) 
	{  
        printf("%d ", p->data);  
        p = p->next;  
    }  
    printf("\n");  }
//销毁
void free_stack(top_p T)
{
	if(T==NULL)
	{
		printf("入参为空\n");
		return;
	}
	link_p del = T->ptop;
	while(T->ptop)
	{
		T->ptop = T->ptop->next;
		free(del);
		del=T->ptop;
	}
	T->ptop=NULL;
}
cpp 复制代码
//main.c
#include "link_stack.h"

int main()
{
	top_p T = create_top();
	push_stack(T,90);
	push_stack(T,23);
	push_stack(T,45);
	push_stack(T,56);
	show(T);
	pop_stack(T);
	show(T);
	printf("判空函数的返回值为--->%d\n",empty_stack(T));
	free_stack(T);
	show(T);
	return 0;
}

思维导图

相关推荐
青山木2 分钟前
Hot 100 --- 下一个排列
java·数据结构·算法·leetcode
SelectDB技术团队1 小时前
Apache Doris 高性能 Open Lake Variant 读写技术解析(含对比数据)
数据结构·数据库·clickhouse·日志·apache doris·selectdb·湖仓架构升级
kiracrimson2 小时前
希尔排序:让插入排序不再怕逆序
数据结构·算法·排序算法
Logic1012 小时前
C语言/数据结构位运算题解:异或XOR找出星球探险中的“独特能量石“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
hnjzsyjyj4 小时前
洛谷 P1339:[USACO09OCT] Heat Wave G ← Bellman-Ford 算法
数据结构·bellman-ford 算法
SelectDB技术团队6 小时前
ClickHouse 存日志的能力边界:并发、检索与 trace 回放的实测对照
数据结构·数据库·clickhouse·日志分析·apache doris·日志存储
垆边人似月.6 小时前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode
w_zero_one7 小时前
链表(2)
java·数据结构·链表
kukubuzai7 小时前
二分查找系列一
数据结构·算法·leetcode
wzdark8 小时前
算法与数据结构教学的可视化新模式探索4
数据结构