【数据结构/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;
}
相关推荐
_F_y16 小时前
链表:重排链表、合并 K 个升序链表、K 个一组翻转链表
数据结构·链表
leaves falling16 小时前
c语言单链表
c语言·开发语言
xu_yule16 小时前
算法基础—组合数学
c++·算法
独自破碎E16 小时前
【中心扩展法】LCR_020_回文子串
java·开发语言
XLYcmy16 小时前
一个用于统计文本文件行数的Python实用工具脚本
开发语言·数据结构·windows·python·开发工具·数据处理·源代码
方便面不加香菜17 小时前
数据结构--链式结构二叉树
c语言·数据结构
4311媒体网17 小时前
自动收藏功能的实现方法
java·开发语言
senijusene17 小时前
数据结构:单向链表(2)以及双向链表
数据结构·链表
xyq202417 小时前
SQLite 创建表
开发语言