gpt4 book ai didi

c - 是否可以将结构存储到链表中?

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:59 25 4
gpt4 key购买 nike

我正在编写一个使用 DFS 算法和堆栈解决迷宫问题的程序。我正在考虑将用于到达终点的路径的坐标存储到包含整数 x,y 坐标的结构中,然后将该结构插入堆栈以执行关于(打印、弹出等)的其他说明。

我找遍了所有地方,但还没有找到任何有用的东西。所以我继续进行设置,但是我收到了一个关于类型兼容性的错误,因为我的节点数据是一个 int,但我试图放入一个结构。作为链表的新手,我只将数据视为 int 或 char。最后,我什至可以做我想做的事吗?如果不能,您能否建议一种将 xy 坐标传递到堆栈的方法?先感谢您。

这是我的代码示例,节省空间的地方 a1COORD 的一个实例,列表和迷宫等都已初始化。

typedef struct node {
int data; /* Value or data stored in node*/
struct node *pNext; /* Reference to the next node address */
} NODE;

/*Structure declares pointers for front and back of the list*/
typedef struct LIST {
NODE *front;
NODE *back;
} LIST;

/* Structure to pass multiple values onto stack */
typedef struct COORD{
int x;
int y;
}COORD;

/*Example of one of the functions */
void lst_push_front(LIST *l, COORD *a1) {
NODE *p = malloc(sizeof(NODE));

p->data = a1;
p->pNext = l->front;

l->front = p;
if(l->back == NULL) // was empty, now one elem
l->back = p;
}

最佳答案

检查下面的代码。

由于 COORD 是一个结构,您可以将其包含在另一个结构中,如下面的代码所示。

还要确保结构的顺序正确。p->data.x 是访问结构COORD

成员的正确方法
#include <stdio.h>

/* Structure to pass multiple values onto stack */
typedef struct COORD{
int x;
int y;
}COORD;

typedef struct node {
COORD data; /* --> Changes done here */
struct node *pNext; /* Reference to the next node address */
} NODE;

/*Structure declares pointers for front and back of the list*/
typedef struct LIST {
NODE *front;
NODE *back;
} LIST;


void func(COORD *q)
{
NODE *p = malloc(sizeof(NODE));
p->data.x = q->x;
p->data.y = q->y;

printf("%d %d",p->data.x,p->data.y);
free(p);
}

int main(void) {

COORD *q = malloc(sizeof(COORD));
q->x = 20;
q->y = 30;
func(q);
free(q);
return 0;
}

关于c - 是否可以将结构存储到链表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28471973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com