0
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 但是我得到一个无限循环......

4

5 回答 5

2

我不完全清楚你想要什么。如果你想要一个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];
}

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

于 2011-12-14T14:57:03.510 回答
1

您确实可以期望得到所有想要的输出,但这不会实现。

你很清楚地创建了两个节点,令人困惑地重复使用v这样做。

我不完全确定您要做什么。但是清理代码以消除两行阅读t = v;可能会澄清您正在发生的事情。

如果你想v->next指向它自己,你需要让它这样做。如果你想要一个节点,你必须构造你的代码,以便malloc()只调用一次。

请记住,Vertex *v;不声明顶点;它声明了一个指向顶点的指针。

于 2011-12-14T12:55:14.637 回答
1

你应该提供整个代码,看看你如何使用函数和列表。实际的错误可能在其他地方。如果到达列表的末尾,您如何比较?

通常next分配链表的最后一个节点的指针NULL。这不太可能导致无限循环。


通常你会做这样的事情:

void buildList(){
  // the list base
  adj[0] = malloc(1*sizeof(*v));
  adj[0]->num = 1;
  adj[0]->next = adj[0]; // <-- make the last node point to itself

  // append more items to the end of the list
  Vertex *v=adj[0];
  while (v != v->next) v = v->next; // <-- find the end of the list
  int i;
  int num_nodes = 1; // <-- specify the number of nodes you want in total
  for (i = 1; i < num_nodes; i++) {
    // append another item
    v->next = malloc(1*sizeof(*v)); 
    // initialize it
    v = v->next;
    v->num = i; 
    v->next = v; // <-- make the last node point to itself
  }
}

而您描述的无限循环可能来自您将列表基分配到列表末尾的事实。从而有效地使列表成为一个循环。

于 2011-12-14T12:55:16.757 回答
1

您可以分析代码片段如下:

    您通过分配指针 v 来分配它。并为其赋值 1 。注意指向下一个元素的指针 ,v->next 未初始化
    然后将 v 复制到 adj[0] 和 t。并且再次发生 v 的重新初始化,(我认为这是多余的),设置其值并将其值复制到 t->next
    到目前为止,您必须 t 指向自身,即 1 指向 1 。但是当您再次将 t 重新初始化为 v 时,具有 v->next 未初始化的 v 导致 t->next 也因此未初始化指向 iyself 的变量现在是不可能的
    在代码的注释部分中,与 adj[0] 是 v 发生了同样的事情。因此,关于无限循环,这是由于在您的工作中使用了上述代码段,当单独运行时,您在访问时会出现分段错误t->下一个
于 2011-12-14T14:42:57.890 回答
0

已经提交的代码看起来只是创建了 2 个单独的节点,然后您只是重新分配了节点 t=v,这使得指针仅指向一个节点。

节点 1 的备份,在阵列上并不清楚及其背后的原因。

如果您能解释您试图实现的逻辑,那就太好了。

于 2011-12-14T13:14:49.790 回答