C 判断链表中是否存在某个值

标签 c list pointers

我正在尝试编写一个方法来查找给定值是否存在于链接列表中。

// 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/

相关文章:

c - 服务器客户端程序未定义行为

c++ - 将 void * 指向 char 作为 int 读取有多安全?

c - 为什么我可以更改 const char *ptr 的内容?

c - 从 C 程序中使用 $EDITOR 变量打开文件进行编辑

c - Glade 布局在编译/GTK_IS_APPLICATION 断言失败时不反射(reflect)

html - 列表样式 none 不应用 + li 边框

c# - 循环获取 PDF 文件

python - 使用 Itertools 循环有困难

delphi - 如何对类型列表进行排序

c++ - 其他结构内部的结构和双指针,多层混淆