【数据结构/C++】栈和队列_链栈

链头 == 栈顶。

cpp 复制代码
#include<iostream>
using namespace std;
// 链栈
typedef int ElemType;
typedef struct Linknode {
  ElemType data;
  struct Linknode *next;
} *LiStack;
// 初始化
void InitLiStack(LiStack &S) {
  S = (LiStack)malloc(sizeof(struct Linknode));
  S->next = NULL;
}
// 入栈
bool PushLiStack(LiStack &S, ElemType x) {
  LiStack p = (LiStack)malloc(sizeof(struct Linknode));
  p->data = x;
  p->next = S->next;
  S->next = p;
  return true;
}
// 出栈
bool PopLiStack(LiStack &S, ElemType &x) {
  if (S->next == NULL) return false;
  LiStack p = S->next;
  x = p->data;
  S->next = p->next;
  free(p);
  return true;
}
// 遍历
void TraverseLiStack(LiStack S) {
  LiStack p = S->next;
  while (p != NULL) {
    cout << p->data << " ";
    p = p->next;
  }
  cout << endl;
}
// 求链栈长度
int StackLength(LiStack S) {
  int length = 0;
  LiStack p = S->next;
  while (p != NULL) {
    length++;
    p = p->next;
  }
  return length;
}
int main() {
  LiStack S;
  ElemType x;
  InitLiStack(S);
  PushLiStack(S, 1);
  PushLiStack(S, 2);
  PushLiStack(S, 3);
  PopLiStack(S, x);
  cout << "出栈元素:" << x << endl;
  TraverseLiStack(S);
  cout << "链栈长度:" << StackLength(S) << endl;
  return 0;
}
相关推荐
知识分享小能手25 分钟前
C++ 学习教程,从入门到精通,C++ 友元、异常和其他特性 — 详细知识点(15)
开发语言·c++·学习
ebiobiz1 小时前
极海 APM32 使用 Nimmake 编译指南
c++·python·单片机·嵌入式硬件·mcu
青山木1 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
朝朝辞暮i1 小时前
C++ 第 26 课:对象、指针与 ->
java·开发语言·c++
2601_962885721 小时前
如何用 Python 做股价历史分位选股?(筛出处于历史低位的股票)
开发语言·python
梦帮科技2 小时前
vLLM / TensorRT-LLM 极限推理:PagedAttention 细粒度物理页表管理与连续批处理(Continuous Batching)实战
数据结构·人工智能·分布式·python·深度学习·算法·vllm
殷色玫瑰2 小时前
C++入门基础复习:从命名空间到引用与nullptr,一篇重新捡回C++基础
java·开发语言·c++
(Charon)2 小时前
【C++面试】手写线程池:任务队列、工作线程与优雅退出
开发语言·c++
言乐62 小时前
Python概括后端原理
开发语言·python·django·virtualenv·pygame
无名猿2 小时前
拷贝构造与拷贝赋值:调用时机、深浅拷贝与复制消除
c++·内存管理·现代c++·踩坑记录