【数据结构/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;
}
相关推荐
aramae3 分钟前
数据结构与算法(递归)
开发语言·经验分享·笔记·算法
小欣加油5 分钟前
leetcode 329 矩阵中的最长递增路径
c++·算法·leetcode·矩阵·深度优先·剪枝
Emilia486.8 分钟前
【Leetcode&nowcode&数据结构】单链表的应用(初阶)
c语言·数据结构·算法·leetcode
千码君201611 分钟前
Go语言:记录一下Go语言系统学习的第一天
java·开发语言·学习·golang·gin·并发编程·编译语言
_给我学起来19 分钟前
字符数组和字符串
c++
Lxinccode39 分钟前
python(48) : 命名截图[Windows工具(3)]
开发语言·python·截图·快速截图
骁的小小站41 分钟前
Learn C the Hardway学习笔记和拓展知识(一)
c语言·开发语言·c++·经验分享·笔记·学习·bash
仰泳的熊猫1 小时前
LeetCode:700. 二叉搜索树中的搜索
数据结构·c++·算法·leetcode
花哥码天下1 小时前
Oracle下载JDK无需登录
java·开发语言