数据结构 链栈

头文件

cpp 复制代码
#pragma once
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
using namespace std;

typedef struct stacknode {
	int data;
	stacknode* next;
}stacknode;
typedef struct linkstack {
	int cursize;
	stacknode* top;
}linkstack;

//1.初始化
void InitStack(linkstack* ps);
//2.栈的元素个数
size_t StackLength(const linkstack* ps);
//3.判空
bool IsEmpty(const linkstack* ps);
//4.入栈
bool Push(linkstack* ps, int val);
//5.打印
void PrintStack(const linkstack* ps);
//6.出栈并获取栈顶元素
bool Pop(linkstack* ps, int* pval);
//7.获取栈顶元素
bool GetTop(linkstack* ps, int* pval);
//8.清空
void ClearStack(linkstack* ps);
//9.销毁
void DestroyStack(linkstack* ps);

源文件

cpp 复制代码
#include"链栈.h"

//1.初始化
void InitStack(linkstack* ps) {
	assert(ps != nullptr);
	ps->cursize = 0;
	ps->top = nullptr;
}
//2.栈的元素个数
size_t StackLength(const linkstack* ps) {
	assert(ps != nullptr);
	return ps->cursize;
}
//3.判空
bool IsEmpty(const linkstack* ps) {
	assert(ps != nullptr);
	return ps->cursize == 0;
}
//4.入栈
bool Push(linkstack* ps, int val) {
	assert(ps != nullptr);
	stacknode* p = (stacknode*)malloc(sizeof(stacknode));
	if (p == nullptr)return false;
	p->data = val;
	p->next = ps->top;
	ps->top = p;
	ps->cursize++;
	return true;
}
//5.打印
void PrintStack(const linkstack* ps) {
	assert(ps != nullptr);
	if (IsEmpty(ps))return;
	for (stacknode* p = ps->top; p != nullptr; p = p->next) {
		cout << p->data << " ";
	}
	cout << endl;
}
//6.出栈并获取栈顶元素
bool Pop(linkstack* ps, int* pval) {
	assert(ps != nullptr&&pval!=nullptr);
	if (IsEmpty(ps))return false;
	*pval = ps->top->data;
	stacknode*p=ps->top;
	ps->top = ps->top->next;
	free(p);
	p = nullptr;
	ps->cursize--;
	return true;
}
//7.获取栈顶元素
bool GetTop(linkstack* ps, int* pval) {
	assert(ps != nullptr);
	if (IsEmpty(ps))return false;
	*pval = ps->top->data;
	return true;
}
//8.清空
void ClearStack(linkstack* ps) {
	assert(ps != nullptr);
	if (IsEmpty(ps))return;
	stacknode* p = ps->top;
	while (p) {
		stacknode* k = p->next;
		free(p);
		p = k;
	}
	p = nullptr;
	ps->cursize = 0;
}
//9.销毁
void DestroyStack(linkstack* ps) {
	assert(ps != nullptr);
	ClearStack(ps);
}

int main() {

	return 0;
}
相关推荐
CSharp精选营1 天前
关系型 vs 非关系型:从原理到选型,一文搞定数据库核心分类
数据结构·nosql·关系型数据库·非关系型数据库·技术选型
刘马想放假5 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
北域码匠6 天前
冒泡排序太慢?鸡尾酒排序双向优化,原生 C# 零第三方库完整代码
数据结构·排序算法·泛型·c# 算法·鸡尾酒排序·原生 c# 开发·冒泡排序优化·嵌入式算法
Darling噜啦啦12 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
小小工匠13 天前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
玖玥拾13 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
Qres82114 天前
算法复键——树状数组
数据结构·算法
牛油果子哥q14 天前
并查集(DSU)超精讲,路径压缩、按秩合并、万能模板、连通性判定、最小生成树与刷题实战全解
数据结构·c++·最小生成树·并查集
凌波粒14 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
WL学习笔记14 天前
单项不带头不循环链表
数据结构·链表