Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
(在C中)为什么这两个列表的合并,除了合并之外,还添加了很多无用的节点?_C_List_Memory_Linked List - Fatal编程技术网

(在C中)为什么这两个列表的合并,除了合并之外,还添加了很多无用的节点?

(在C中)为什么这两个列表的合并,除了合并之外,还添加了很多无用的节点?,c,list,memory,linked-list,C,List,Memory,Linked List,结构规范: typedef struct nodo_int *lista_int; struct nodo_int{ int info; lista_int next; }nodo_int; 用于可视化列表并将其合并为一个列表的代码: void visNode(int value){ printf("| %d |", value); } void visList(lista_int l){ if(l != NULL){ visNode(l-

结构规范:

typedef struct nodo_int *lista_int;

struct nodo_int{
    int info;
    lista_int next;
}nodo_int;

用于可视化列表并将其合并为一个列表的代码:

void visNode(int value){
    printf("| %d |", value);
}

void visList(lista_int l){
    if(l != NULL){
        visNode(l->info);
        visList(l->next);
    }
}

lista_int alternateLists(lista_int l1, lista_int l2){
    lista_int l3 = makesNode();
    lista_int temp = l3, newNode = NULL;

    if(l1 == NULL)
        return l2;
    else if(l2 == NULL)
        return l1;

    while(l1 != NULL && l2 != NULL){
        newNode = makesNode();
        newNode->info = l1->info;
        temp->next = newNode;
        temp = newNode;
        l1 = l1->next;

        newNode = makesNode();
        newNode->info = l2->info;
        temp->next = newNode;
        temp = newNode;
        l2 = l2->next;
        printf("\n1\n");

    }

    return l3->next;
} 
大体上:

int main(){
    lista_int l1, l2;
    l1 = generateList();
    l2 = generateList();    
    printf("\nFirst list:\n");
    visList(l1);
    printf("\n\nSecond lists:\n");
    visList(l2);
    printf("\n\nNew list obtained from merging the other two:\n");
    lista_int l3 = alternateLists(l1, l2);
    visList(l3);
    return 0;
}

代码做了它应该做的,但是也给第三个列表添加了很多无用的内存。我也尝试过调试,但结果是误报。

什么导致误报?您的结构定义是否缺少一个
typedef
?我的意思是调试没有给我任何答案,但出于某些原因,列表中仍然充满了无用的节点提示:键入defing一个指针,如
typedef struct nodo_int*lista_int有助于混淆代码-更难调试。考虑<代码> TyPulfStrut NodoItListaItIn;<代码>(否*)下次。快速查看,我没有看到“很多”额外的节点被创建,但您正在
alternateLists()
中泄漏内存,因为您在
l3
的开头分配了一个虚拟节点,该节点不在您返回的列表部分之外。另外,如果
l1
l2
列表的长度不同,您不会从较长列表的末尾复制节点,这是有意的吗?