数据结构:链栈

一、介绍

操作受限的链表

如果进行头插,就只能头删

如果进行尾插,就只能进行尾删

二、功能(把T->ptop当做头节点用)

链栈的结构体

cs 复制代码
#ifndef __LINK_STACK_H__
#define __LINK_STACK_H__
#include <stdio.h>
#include <stdlib.h>
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 creat_top();
//申请节点的函数
link_p creat_node(int data);
//判空
int empty(top_p T);
//入桟
void push_stack(top_p T,int data);
//出桟
void pop_stack(top_p T);
//遍历
void show_stack(top_p T);
//销毁链桟
void free_stack(top_p T);

#endif

1.申请栈顶指针

cs 复制代码
//申请桟顶指针
top_p creat_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;
}

2.申请节点

cs 复制代码
//申请节点的函数
link_p creat_node(int data){
	link_p new=(link_p)malloc(sizeof(link_stack));
	if(new==NULL){
		printf("申请空间失败\n");
		return NULL;
	}
	new->data=data;
	return new;
}

3.判空

cs 复制代码
//判空
int empty(top_p T){
		if(T==NULL){
		printf("申请空间失败\n");
		return 0;
	}
		return T->ptop==NULL?1:0;

}

4.入栈

cs 复制代码
//入桟
void push_stack(top_p T,int data){
	if(T==NULL){
		printf("入参为空\n");
		return;
	}
	link_p new=creat_node(data);
	new->next=T->ptop;
	T->ptop=new;
	T->len++;
}

5.出栈

cs 复制代码
void pop_stack(top_p T){
	if(T==NULL){
		printf("入参为空\n");
		return;
	}
	if(empty(T)){
printf("链桟为空,无需出桟\n");
return;
	}
	link_p p=T->ptop;
	while(p->next->next!=NULL){
		p=p->next;
	}
	link_p del=p->next;
	p->next=del->next;
	free(del);
	T->len--;
}

6.遍历

cs 复制代码
//遍历
void show_stack(top_p T){
	if(T==NULL){
		printf("入参为空\n");
		return;
	}
if(empty(T)){
	printf("链桟为空\n");
	return;
}
link_p p=T->ptop;
while(p!=NULL){
	printf("%d ",p->data);
	p=p->next;
}
putchar(10);
}

7.销毁链栈

复制代码
//销毁链桟
void free_stack(top_p T){
	if(T==NULL){
		printf("入参为空\n");
		return;
	}
	if(empty(T)){
		printf("链桟为空\n");
		return;
	}
	//循环出桟
	link_p p=T->ptop->next;
	link_p del;
	while(p!=NULL){
		del=p;
		p=p->next;
		free(del);
		del=NULL;
	}

}
相关推荐
LuminousCPP1 天前
数据结构‑二叉树(二):二叉堆从零实现|Heap结构设计 + 建堆优化 + 堆排序深度解析
c语言·数据结构·笔记·二叉树
1 天前
数据结构第一课:复杂度解析
数据结构
欧叶冲冲冲1 天前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
_Narcissus_1 天前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.1 天前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
疯狂打码的少年1 天前
【数据结构】八大排序算法对比总结(时间/空间/稳定性)
数据结构·笔记·算法
Awh-1 天前
数据结构 第六章:哈希存储
数据结构·算法·哈希算法
TAN-90°-1 天前
Deep Learning for Computer Vision——Recurrent Neural Networks
数据结构·人工智能·rnn·深度学习·神经网络·机器学习·计算机视觉
wabs6661 天前
关于栈【力扣150.逆波兰表达式求值的思考】
数据结构·c++·算法·leetcode··代码随想录
闻缺陷则喜何志丹2 天前
【计算几何 第10章】更多几何数据结构:截窗
数据结构·数学·线段树·计算几何·截窗·优先查找树·区间树