我正在尝试访问一个链表数组。如果在列表数组的某个索引处没有列表,则需要为该链表的第一个元素创建一个新节点。我知道我的if语句不能正常工作,
if ( arrayOfLists[label] == NULL ) 我的节点结构是:
struct node {
int x;
node *next;
};当我运行我的程序时,我陷入了一个无限的while循环。也就是说,在此函数中,输出为:
cout << "x value " << hopper -> x << endl;最终变成"x值603“,永远重复。
void Union(int largerLabel, int label, struct node * arrayOfLists[], struct node * hopper) {
cout << "union called" << endl;
if ( arrayOfLists[label] == NULL )
{
// cout << "if # 1" << endl;
arrayOfLists[label] = new node;
arrayOfLists[label] -> next = NULL;
arrayOfLists[label] -> x = largerLabel;
}
else {
// cout << "else # 1" << endl;
hopper = arrayOfLists[ label ];
while ( hopper -> next != NULL )
{
// cout << "x value " << hopper -> x << endl;
if ( largerLabel == hopper -> x )
{
cout << "return " << endl;
return;
}
hopper = hopper -> next;
}
if ( arrayOfLists[largerLabel] != NULL )
{
// cout << "if # 2" << endl;
hopper -> next = arrayOfLists[largerLabel];
}
else
{
// cout << "else # 2" << endl;
hopper -> next = new node;
hopper = hopper -> next;
hopper -> x = largerLabel;
hopper -> next = NULL;
}
}
cout << "return" << endl;
return;
}发布于 2014-07-03 03:21:01
很难说你试图实现什么,但无限执行清楚地表明你在列表中有一个循环。例如下面的代码:
if ( arrayOfLists[largerLabel] != NULL )
{
// cout << "if # 2" << endl;
hopper -> next = arrayOfLists[largerLabel];
}如果标签为NULL,largerLabel和arrayOfListslable != NULL肯定会创建一个循环。它也可以在其他条件下使用。这段代码看起来不对劲。
https://stackoverflow.com/questions/24539137
复制相似问题