欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > 栈的学习笔记

栈的学习笔记

2025/4/19 10:04:25 来源:https://blog.csdn.net/2301_79790385/article/details/147257369  浏览:    关键词:栈的学习笔记

使用数组实现一个栈

#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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词