【数据结构/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;
}
相关推荐
future14125 分钟前
游戏开发日记
数据结构·学习·c#
ydm_ymz26 分钟前
C语言初阶4-数组
c语言·开发语言
presenttttt35 分钟前
用Python和OpenCV从零搭建一个完整的双目视觉系统(六 最终篇)
开发语言·python·opencv·计算机视觉
wjcurry36 分钟前
完全和零一背包
数据结构·算法·leetcode
逐花归海.36 分钟前
『 C++ 入门到放弃 』- 多态
开发语言·c++·笔记·程序人生
卜锦元1 小时前
Go中使用wire进行统一依赖注入管理
开发语言·后端·golang
qq_433554541 小时前
C++ 选择排序、冒泡排序、插入排序
数据结构
python_tty1 小时前
排序算法(一):冒泡排序
数据结构·算法·排序算法
卡卡_R-Python2 小时前
C++编程基础
c++
军训猫猫头2 小时前
3.检查函数 if (!CheckStart()) return 的妙用 C#例子
开发语言·c#