当前位置: 首页 > news >正文

栈的学习笔记

使用数组实现一个栈

#include <stdio.h>#define MAX_SIZE 101int A[MAX_SIZE];
int top = -1;  //栈顶指针,初始为-1,表示栈为空
void push(int x)
{if (top == MAX_SIZE - 1){printf("栈已满,无法入栈\n");return;}A[++top] = x;
}void pop()
{if (top == -1){printf("栈已空,无法出栈\n");return;}top--;
}void Print()
{for (int i = 0; i <= top; i++){printf("%d ", A[i]);}printf("\n");
}int Top()
{if (top == -1){printf("栈已空,无法取栈顶元素\n");return -1;}return A[top];
}int main()
{push(2);Print();push(5);Print();push(10);Print();pop();Print();push(12);Print();
}

使用链表实现一个栈

链表的头部(头指针)当作栈顶(top)

#include <stdio.h>
#include <stdlib.h>// 定义链式栈节点结构体
struct Node {int data;struct Node* link;
};// 全局变量,指向栈顶
struct Node* top = NULL;// 入栈操作
void push(int x) {// 分配内存并检查是否分配成功struct Node* temp = (struct Node*)malloc(sizeof(struct Node));if (temp == NULL) { // 检查内存分配是否成功printf("Memory allocation failed\n");return;}temp->data = x; // 设置数据域temp->link = top; // 链接原栈顶top = temp; // 更新栈顶指针
}// 出栈操作
void pop() {if (top == NULL) { // 栈为空时处理printf("Stack is empty\n");return;}struct Node* temp = top; // 保存当前栈顶top = top->link; // 更新栈顶指针free(temp); // 释放原栈顶节点内存
}// 打印栈内容
void Print() {struct Node* temp = top;if (temp == NULL) { // 栈为空时处理printf("Stack is empty\n");return;}while (temp != NULL) { // 遍历栈并打印printf("%d ", temp->data);temp = temp->link;}printf("\n");
}// 主函数
int main() {push(2); Print(); // 打印栈内容push(5); Print();push(10); Print();pop(); Print();push(12); Print();return 0;
}

相关文章:

  • Spring Cloud 服务间调用深度解析
  • 数据库之MySQL
  • MySQLQ_数据库约束
  • Android系统通知机制深度解析:Framework至SystemUI全链路剖析
  • 4.15学习总结
  • Java 基本操作快速入门:理解与实践
  • 编程语言到mysql ‘\‘到数量关系
  • c++模版进阶
  • 11.第二阶段x64游戏实战-框架代码细节优化
  • mysql按条件三表并联查询
  • C语言进阶之自定义类型:结构体,枚举,联合
  • 关于TD算法的笔记【时间差分】
  • 小程序接口使用时,HttpOnly cookie 中的 sameSite 设置什么最合适
  • Redis入门(Java中操作Redis)
  • JavaWeb 课堂笔记 —— 11 MySQL 多表设计
  • HashMap为什么从java8的时候从头插变为尾插了
  • 利用代理 IP 突破反爬限制,实现跨境电商数据高效爬取
  • C++: Initialization and References to const 初始化和常引用
  • 数字ic后端设计从入门到精通(含fusion compiler, tcl教学)
  • C语言自定义类型详解一:结构体(内存对齐)
  • 喝水呛咳?帕金森患者的吞咽障碍看这一篇就够了
  • 生于1984年,郭宝任湖北黄石市副市长
  • 中国足协、中足联:对中超浙江队外援阿隆·布彭扎不幸离世表示深切哀悼
  • 支持民营企业上市融资,上海将有什么新举措?
  • 沪指尾盘急涨翻红:大消费、大金融走强,多只银行股创历史新高