【数据结构/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;
}
相关推荐
ZZZ_O^O17 分钟前
二分查找算法——寻找旋转排序数组中的最小值&点名
数据结构·c++·学习·算法·二叉树
代码雕刻家1 小时前
数据结构-3.9.栈在递归中的应用
c语言·数据结构·算法
吾爱星辰2 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
ChinaDragonDreamer2 小时前
Kotlin:2.0.20 的新特性
android·开发语言·kotlin
IT良2 小时前
c#增删改查 (数据操作的基础)
开发语言·c#
小飞猪Jay2 小时前
C++面试速通宝典——13
jvm·c++·面试
Kalika0-03 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch3 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
代码雕刻家3 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
一个闪现必杀技3 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm