检查list2是否包含list1

Check if list2 contains list1

这个函数应该检查 list1 是否包含在列表 2 中,在这种情况下 return1。我不确定为什么我总是得到输出 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;

没有

const struct node *node;