实现顺序栈的各种基本运算;其次设计程序调用顺序栈的这些算法进行功能测试。用c语言
时间: 2024-12-08 19:17:27 浏览: 15
括号匹配流程图-c语言 栈的顺序和链式实现代码ppt
在 C 语言中,我们可以创建一个简单的顺序栈数据结构,并实现常见的栈操作,如压入元素(push)、弹出元素(pop)、查看顶部元素(peek 或 top)以及检查栈是否为空(is_empty)。这里是一个基础的顺序栈实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义栈的最大容量
#define MAX_CAPACITY 50
// 结构体定义栈
typedef struct Stack {
int capacity;
int* items; // 存储栈元素的数组
int top; // 栈顶指针
} Stack;
// 初始化栈
Stack* stack_create() {
Stack* s = (Stack*)malloc(sizeof(Stack));
if (!s) {
printf("Memory allocation failed.\n");
return NULL;
}
s->capacity = MAX_CAPACITY;
s->items = (int*)malloc(s->capacity * sizeof(int));
if (!s->items) {
free(s);
printf("Memory allocation for items failed.\n");
return NULL;
}
s->top = -1;
return s;
}
// 空栈检测
int is_empty(Stack* s) {
return s->top == -1;
}
// 入栈(push)
void push(Stack* s, int value) {
if (s->top == s->capacity - 1) {
printf("Stack is full, can't push.\n");
return;
}
s->items[++s->top] = value;
}
// 出栈(pop)
int pop(Stack* s) {
if (is_empty(s)) {
printf("Stack is empty, can't pop.\n");
return -1;
}
return s->items[s->top--];
}
// 查看栈顶元素(peek)
int peek(Stack* s) {
if (is_empty(s)) {
printf("Stack is empty, no element to peek.\n");
return -1;
}
return s->items[s->top];
}
// 销毁栈
void stack_destroy(Stack* s) {
free(s->items);
free(s);
}
int main() {
Stack* stack = stack_create();
// 功能测试
if (!stack) {
return 1;
}
push(stack, 1);
push(stack, 2);
push(stack, 3);
printf("Top element: %d\n", peek(stack)); // 输出: Top element: 3
printf("Popped element: %d\n", pop(stack)); // 输出: Popped element: 3
printf("After popping: Top element is %d\n", peek(stack)); // 输出: After popping: Top element is 2
stack_destroy(stack);
return 0;
}
```
阅读全文