数据结构 链栈

头文件

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 分钟前
数据结构 二叉树核心概念与特性
数据结构·算法
皮皮哎哟8 分钟前
数据结构:从队列到二叉树基础解析
c语言·数据结构·算法·二叉树·队列
一匹电信狗16 分钟前
【高阶数据结构】并查集
c语言·数据结构·c++·算法·leetcode·排序算法·visual studio
Hello World . .1 小时前
数据结构:二叉树(Binary tree)
c语言·开发语言·数据结构·vim
DeeplyMind1 小时前
少儿科技启蒙教材:《数据结构启蒙》
数据结构·计算机科学·少儿科技读物·蓝桥杯青少组
划破黑暗的第一缕曙光2 小时前
[数据结构]:6.二叉树链式结构的实现2
c语言·数据结构·二叉树
浅念-2 小时前
C语言——自定义类型:结构体、联合体、枚举
c语言·开发语言·数据结构·c++·笔记·学习·html
仰泳的熊猫2 小时前
题目1433:蓝桥杯2013年第四届真题-危险系数
数据结构·c++·算法·蓝桥杯·深度优先·图论
cyforkk2 小时前
14、Java 基础硬核复习:数据结构与集合源码的核心逻辑与面试考点
java·数据结构·面试
试试勇气2 小时前
算法工具箱之哈希表
数据结构·算法·散列表