在C语言中,可以使用数组来表示堆栈结构,并通过指针来操作堆栈。要显示堆栈结构中的每个元素,可以按照以下步骤进行:
#define MAX_SIZE 100
typedef struct {
int capacity;
int size;
int* elements;
} Stack;
Stack* initStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->capacity = MAX_SIZE;
stack->size = 0;
stack->elements = (int*)malloc(MAX_SIZE * sizeof(int));
return stack;
}
void push(Stack* stack, int element) {
if (stack->size >= stack->capacity) {
printf("Stack is full.\n");
return;
}
stack->elements[stack->size++] = element;
}
int pop(Stack* stack) {
if (stack->size <= 0) {
printf("Stack is empty.\n");
return -1;
}
return stack->elements[--stack->size];
}
void display(Stack* stack) {
if (stack->size <= 0) {
printf("Stack is empty.\n");
return;
}
printf("Stack elements: ");
for (int i = 0; i < stack->size; i++) {
printf("%d ", stack->elements[i]);
}
printf("\n");
}
通过调用上述函数,可以实现显示堆栈结构中每个元素的功能。以下是一个示例程序:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int capacity;
int size;
int* elements;
} Stack;
Stack* initStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->capacity = MAX_SIZE;
stack->size = 0;
stack->elements = (int*)malloc(MAX_SIZE * sizeof(int));
return stack;
}
void push(Stack* stack, int element) {
if (stack->size >= stack->capacity) {
printf("Stack is full.\n");
return;
}
stack->elements[stack->size++] = element;
}
int pop(Stack* stack) {
if (stack->size <= 0) {
printf("Stack is empty.\n");
return -1;
}
return stack->elements[--stack->size];
}
void display(Stack* stack) {
if (stack->size <= 0) {
printf("Stack is empty.\n");
return;
}
printf("Stack elements: ");
for (int i = 0; i < stack->size; i++) {
printf("%d ", stack->elements[i]);
}
printf("\n");
}
int main() {
Stack* stack = initStack();
push(stack, 1);
push(stack, 2);
push(stack, 3);
display(stack);
pop(stack);
display(stack);
return 0;
}
输出结果为:
Stack elements: 1 2 3
Stack elements: 1 2
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云