使用数组实现一个栈
#include <stdio.h>
#define MAX_SIZE 101
int 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;
}