C 检查列表2是否包含列表1

C 检查列表2是否包含列表1,c,function,struct,linked-list,singly-linked-list,C,Function,Struct,Linked List,Singly Linked List,这个函数应该检查列表1是否包含在列表2中,在这种情况下返回1。我不知道为什么我总是得到输出0。 欢迎所有反馈 typedef struct node { int data; struct node *next; } *list; int contains (list l1, list l2) { int check; while(l1 != NULL){ check = 0; while(l2 != NULL){ if(l1->data =

这个函数应该检查列表1是否包含在列表2中,在这种情况下返回1。我不知道为什么我总是得到输出0。 欢迎所有反馈

typedef struct node {
  int data;
  struct node *next;
} *list;


int contains (list l1, list l2)
{
  int check;
  while(l1 != NULL){
    check = 0;

    while(l2 != NULL){
      if(l1->data == l2->data)
        check = 1;

      l2 = l2->next;
    }

    if(check == 0)
      return 0;

    l1 = l1->next;
  }
  return 1;
}

当从第一个列表中找到节点的值时,不会中断内部循环

在内部循环中,也不会将第二个列表重新定位到其开头

该函数可以通过以下方式定义

int contains( list l1, list l2 )
{
    int check = 1;

    for ( ; check && l1 != NULL; l1 = l1->next )
    {
        check = 0;

       for ( link current = l2; !check && current != NULL; current = current->next )
       {
           if ( l1->data == current->data ) check = 1;
       }
    }

    return check;
}
该函数不检查第一个列表中是否存储了重复的值

请注意,将typedef定义为

typedef struct node {
  int data;
  struct node *next;
} *list;
这是个坏主意。如果需要指向常量节点的指针,则无法写入

const link node;
因为这意味着

struct node * const node;
不是


你是用调试器调试的吗?当检查l1的元素超过第一个元素时,您没有将l2指针重置为列表的开头。@johneleman就是这样!非常感谢。
const struct node *node;