此函数应该检查列表 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;
不是
const struct node *node;
关于检查list2是否包含list1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57826043/