C++ 将linkedlist组织到C++;

C++ 将linkedlist组织到C++;,c++,arrays,pointers,linked-list,C++,Arrays,Pointers,Linked List,我正在编写一个方法,该方法采用一个函数,该函数取链表的根和图中的顶点数,并基于边结构的第一个顶点将链表组织成一个链表数组,例如,在一个结构中,节点边的firVertex=1、sndVertex=2和weight=2,它将被排序到数组的第一个元素中。另一个具有另一个firVertex=1的节点边缘将附加到前一个节点边缘上,以此类推。我的代码可以编译,但它并不是我想要的。请帮忙 您的代码中有许多问题 将newNode分配给数组列表的元素时,应 arrayList[j]= newNode; //not

我正在编写一个方法,该方法采用一个函数,该函数取链表的根和图中的顶点数,并基于边结构的第一个顶点将链表组织成一个链表数组,例如,在一个结构中,节点边的firVertex=1、sndVertex=2和weight=2,它将被排序到数组的第一个元素中。另一个具有另一个firVertex=1的节点边缘将附加到前一个节点边缘上,以此类推。我的代码可以编译,但它并不是我想要的。请帮忙

您的代码中有许多问题

newNode
分配给数组列表的元素时,应

arrayList[j]= newNode; //not 'i' since i=numberVertices always....
当您找到与
j
匹配的
firVertex
时,您正在创建一个指向当前节点的临时指针。那么你是这样做的:

newNode -> next = NULL;
它实际上会将给定列表中节点的
next
更改为
NULL
,从而使
当前->next
变为
NULL
,您的代码不会处理整个列表。应改为如下:

Edge* newNode = new Edge(current);//create a copy of the 'current' node..
newNode -> next = NULL;//now make the 'next' of this node NULL..
Edge* newNode = new Edge(current);
newNode -> next = NULL;
Edge* tmp = arrayList[j];
if(tmp==NULL)//then this is the first node..
{
     arrayList[j] = new Edge(current);
     arrayList[j]->next = NULL;
}
else
{
    while(tmp->next!=NULL)//go to the end of the list...
      tmp = tmp->next;
   tmp->next = new Edge(current);//create a copy of the 'current' node...
   tmp->next->next=NULL;//make the next of this new node NULL...
}
上述代码阻止对列表进行任何修改。我还假设有一个
Edge
的构造函数,它使用另一个
Edge
指针作为参数

如问题中所述,如果有两个
Edge
节点具有相同的
firVertex
,则需要将它们附加到相同的列表中。但是您的代码仅仅覆盖了上一个节点。 为防止出现这种情况,可将其写为:

Edge* newNode = new Edge(current);//create a copy of the 'current' node..
newNode -> next = NULL;//now make the 'next' of this node NULL..
Edge* newNode = new Edge(current);
newNode -> next = NULL;
Edge* tmp = arrayList[j];
if(tmp==NULL)//then this is the first node..
{
     arrayList[j] = new Edge(current);
     arrayList[j]->next = NULL;
}
else
{
    while(tmp->next!=NULL)//go to the end of the list...
      tmp = tmp->next;
   tmp->next = new Edge(current);//create a copy of the 'current' node...
   tmp->next->next=NULL;//make the next of this new node NULL...
}

希望这有助于……我强烈地认为你需要更多地学习指针然后开始编码。< /P>看起来你正在返回一个指向局部变量的指针。对于编程和C++来说,我真的是新手。你能给我一个建议吗?关于修复什么?返回STD::向量,如果是C++的话。我觉得代码中还有其他问题。您应该首先学习更多关于C语言中内存管理的知识,而不仅仅是尝试进行修复,您不能在不知道的情况下编写C代码。