利用 C 语言实现栈并获取输出序列167
栈是一种先进后出的线性数据结构,它遵循后进先出的原则,即最后添加的元素将首先被移除。在计算机科学中,栈广泛应用于各种算法和数据处理任务。
为了用 C 语言实现栈,我们需要创建一个数据结构来存储元素。此数据结构应支持以下操作:* Push (入栈):将新元素添加到栈顶。
* Pop (出栈):移除并返回栈顶元素。
* Peek:查看栈顶元素而不将其移除。
* isEmpty:检查栈是否为空。
以下是使用数组实现栈的 C 语言代码片段:```c
#include
#include
// 定义栈结构
struct Stack {
int *array;
int top;
int capacity;
};
// 创建栈
struct Stack *createStack(int capacity) {
struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack));
stack->array = (int *)malloc(capacity * sizeof(int));
stack->top = -1;
stack->capacity = capacity;
return stack;
}
// 检查栈是否为空
int isEmpty(struct Stack *stack) {
return stack->top == -1;
}
// 入栈
void push(struct Stack *stack, int value) {
if (stack->top == stack->capacity - 1) {
printf("栈已满");
return;
}
stack->array[++stack->top] = value;
}
// 出栈
int pop(struct Stack *stack) {
if (isEmpty(stack)) {
printf("栈已空");
return -1;
}
return stack->array[stack->top--];
}
// 查看栈顶元素
int peek(struct Stack *stack) {
if (isEmpty(stack)) {
printf("栈已空");
return -1;
}
return stack->array[stack->top];
}
// 打印栈中所有元素
void printStack(struct Stack *stack) {
if (isEmpty(stack)) {
printf("栈已空");
return;
}
for (int i = stack->top; i >= 0; i--) {
printf("%d ", stack->array[i]);
}
printf("");
}
// 测试栈
int main() {
struct Stack *stack = createStack(5);
push(stack, 1);
push(stack, 2);
push(stack, 3);
push(stack, 4);
push(stack, 5); // 栈已满
printStack(stack); // 输出:5 4 3 2 1
pop(stack);
pop(stack);
pop(stack);
printf("栈顶元素:%d", peek(stack)); // 输出:2
isEmpty(stack) ? printf("栈已空") : printf("栈非空"); // 输出:栈非空
return 0;
}
```
在这个代码中,我们声明了一个名为 Stack 的结构体来表示栈。它包含一个数组来存储元素、一个 top 指针指向栈顶,以及一个 capacity 变量表示栈的最大容量。
createStack() 函数创建并返回一个新栈。isEmpty() 函数检查栈是否为空。push() 函数将元素添加到栈顶。pop() 函数移除并返回栈顶元素。peek() 函数返回栈顶元素。printStack() 函数打印栈中的所有元素。
在 main() 函数中,我们创建了一个容量为 5 的栈,并向其中添加了 5 个元素。然后,我们打印栈中的元素,出栈 3 个元素,并打印栈顶元素。最后,我们检查栈是否为空,并打印结果。
通过使用栈的数据结构,我们可以轻松实现各种算法,例如逆波兰表示法的计算、函数调用中的局部变量分配以及递归算法的实现。
2024-11-27
上一篇:R语言中使用C语言函数加速计算
下一篇:C 语言中简单输入输出操作指南
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html