我正在尝试编写一个方法来查找给定值是否存在于链接列表中。
// Returns true if the value exists in the list.
int llist_exists(LinkedList * list, int value) {
LinkedList *e;
e = list->head;
int result = 0;
while(e != NULL)
{
if(e == value)
{
result = 1;
break;
}
}
return result;
}
最佳答案
在您的代码中,您将指针与 int 进行比较,正如 @xxbbcc 指出的那样,永远不会在列表中向前移动。 如果我们假设您的 LinkedList 类如下:
class LinkedList
{
public:
int value;
LinkedList *next;
};
int llist_exists(LinkedList * list, int value) {
LinkedList *e;
e = list->head;
int result = 0;
while(e != NULL)
{
if(e->value == value)
{
result = 1;
break;
}
e = e->next;
}
return result;
}
关于C 判断链表中是否存在某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28818701/