gpt4 book ai didi

c - 在邻接表中有自己的节点

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

typedef struct vertex{
int num;
struct vertex *next;
} Vertex;

Vertex *adj[1];

void buildList(){
Vertex *v=NULL;
Vertex *t=NULL;

v = malloc(1*sizeof(*v));
v->num = 1;
adj[0] = v; //a NODE with value 1
t = v;

v = malloc(1*sizeof(*v));
v->num = 1;
t->next = v; // and ANOTHER NODE but it should be the SAME NODE with the above one
t = v;


//v = malloc(1*sizeof(*v));
//v->num = 1;
//t->next = adj[0]; // causes infinite loop...
//t = v;
}

预期的输出是一个值为 1 的节点,其自身位于其邻接列表中,输出类似于 1 -> 1。

我的问题是我有两个不同的节点。当我对其中一个进行更改时,另一个不会更改,就像另一个节点一样。

例如,在构建列表后,如果我更改节点的值,我应该得到类似 3 -> 3 的输出。但我得到 3 -> 1。节点上的更改不会影响另一个节点。当我尝试将 adj[0] 指向 t->next 但是我得到一个无限循环......

最佳答案

我不太清楚你想要什么。如果你想要一个指向自身的Vertex,它很简单

void buildList(){
adj[0] = malloc(1*sizeof(*adj[0])); // allocate memory for one Vertex
if (adj[0] == NULL){
perror("Allocation of Vertex failed\n");
exit(EXIT_FAILURE);
}
// adj[0] contains the adress of a Vertex
// set the num of the Vertex
adj[0]->num = 1;
// set the next pointer of the Vertex to its address
adj[0]->next = adj[0];
}

你能澄清一下这不是你想要的吗?

关于c - 在邻接表中有自己的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8504776/

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