数据结构 链栈

头文件

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;
}
相关推荐
启观川3 小时前
数据结构与算法 -第 3 章 常用算法-动态规划
数据结构·笔记·python·算法
Logic1015 小时前
C语言/数据结构欧几里得算法题解:长方形切割最大正方形——贪心划分计数
c语言·数据结构·算法·贪心算法·时间复杂度·空间复杂度·欧几里得算法
flinn_small7 小时前
三分算法:原理、实现与实战应用
数据结构·算法·三分
INGNIGHT8 小时前
944 · 最大子矩阵(前缀和)
数据结构·c++·算法
All for pursuit.8 小时前
【动态规划-6】96.不同的二叉搜索树
数据结构·c++·算法·leetcode·动态规划
信奥卷王9 小时前
[GESP202609 六级] 数组划分
数据结构·算法
All for pursuit.10 小时前
【并查集-2】399.除法求值
数据结构·c++·算法·leetcode
殷色玫瑰13 小时前
AVL树:从平衡因子到四种旋转的完整实现
c语言·数据结构·c++·算法·visualstudio
y1su14 小时前
Leetcode 二分模板
java·数据结构·算法·leetcode·排序算法
bksczm14 小时前
数据结构的大纲概括
数据结构