在Stack结构体中嵌套Point结构体存问题,如何无vector/pair重构代码?
重构存储坐标点的栈结构(不使用vector或pair)
原代码的核心问题在于:栈的存储数组是int类型,无法容纳Point结构体;同时嵌套定义的Point仅为单个成员,而非可存储多个元素的数组。以下是针对迷宫算法需求的重构方案:
方案一:分开定义Point与Stack结构体(推荐,可读性更好)
#include <stdio.h> #define MAX_SIZE 100 // 根据迷宫规模调整栈的最大容量 // 定义坐标点结构体 typedef struct { int x; int y; } Point; // 定义存储坐标点的栈结构体 typedef struct { Point arr[MAX_SIZE]; // 存储多个坐标点的数组 int top; // 栈顶索引,-1表示空栈 } Stack;
方案二:嵌套定义Point结构体
如果坚持要把Point嵌套在Stack内部,可按以下方式编写(注意C语言不支持在struct内部直接用typedef,需直接使用struct Point作为数组类型):
#include <stdio.h> #define MAX_SIZE 100 typedef struct { struct Point { int x; int y; } arr[MAX_SIZE]; // 用struct Point作为数组元素类型 int top; } Stack;
栈的核心操作实现
不管用哪种结构体定义方式,栈的入栈、出栈等操作逻辑一致:
初始化栈
void initStack(Stack *stack) { stack->top = -1; // 空栈状态 }
入栈操作
// 返回1表示入栈成功,0表示栈满失败 int push(Stack *stack, Point p) { if (stack->top == MAX_SIZE - 1) { printf("栈已满,无法添加新坐标\n"); return 0; } stack->arr[++stack->top] = p; return 1; }
出栈操作
// 返回坐标(-1,-1)表示栈空,出栈失败 Point pop(Stack *stack) { Point empty = {-1, -1}; if (stack->top == -1) { printf("栈已空,无法弹出元素\n"); return empty; } return stack->arr[stack->top--]; }
判断栈是否为空
int isEmpty(Stack *stack) { return stack->top == -1; }
使用示例(迷宫路径记录场景)
int main() { Stack pathStack; initStack(&pathStack); // 模拟迷宫路径入栈 Point start = {0, 0}; Point step1 = {0, 1}; Point step2 = {1, 1}; push(&pathStack, start); push(&pathStack, step1); push(&pathStack, step2); // 回溯路径(出栈打印) printf("回溯路径:\n"); while (!isEmpty(&pathStack)) { Point p = pop(&pathStack); printf("(%d, %d)\n", p.x, p.y); } return 0; }
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

