【发布时间】:2014-11-19 06:54:43
【问题描述】:
我正在制作一个由链表实现的图表,但我发现自己有点困惑,因为我确定我没有正确遍历链表。
// A structure to represent an adjacency list node
typedef struct AdjListNode
{
char data;
int distance;
struct AdjListNode* next;
} AdjListNode;
// A structure to represent an adjacency list
typedef struct AdjList
{
char data;
struct AdjListNode* head; // pointer to head node of list
} AdjList;
// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be the number of vertices in graph.
typedef struct Graph
{
int NumberOfNodes;
struct AdjList* array;
} Graph;
所以我正在制作一个具有数组的图,并且数组的每个元素都是链表的头。
但是,当我尝试输出所有元素时,它只打印头部旁边的元素,例如:
A->B5
B->E6
C->A8
D->C2
E->D7
所以在将它们添加到链表时会出错,因为它应该是
A->B5->D5-C7
B->E6->E4
C->A8
D->C2->B6->A2
E->D7
这是函数的 sn-p,它将节点添加到图中我相信 else 语句有错误
for(i =0; i < G->NumberOfNodes ; i++)
{
if(G->array[i].data == from)
{ // if the letter from the primary array matches the letter that needs to be added to
if(G->array[i].head == NULL)
{ // if the head node of the linked list is empty simply just and the element there
G->array[i].head = malloc(sizeof(AdjListNode));
G->array[i].head->data = to;
G->array[i].head->distance = number;
G->array[i].head->next = NULL;
}
else
{ // if the head is not empty then this will find another position for it
AdjListNode* looker;
looker = G->array[i].head;
while(looker != NULL)
{
looker = looker->next; // pointing to the next position
}
looker = malloc(sizeof(AdjListNode)); // placing the element on that position
looker->data = to;
looker->distance = number;
looker->next = NULL;
free(looker);
}
}
}
【问题讨论】:
-
你有没有调试过?
-
不,我不知道如何完全使用 de gdb...但我几乎 90% 确定错误出在 addEdge 函数上,即使用“looker”变量的 else 语句
-
感谢 UniCell!对于那个编辑
标签: c algorithm pointers linked-list graph-algorithm