【问题标题】:change the start address of two linked lists with one function一个函数改变两个链表的起始地址
【发布时间】:2025-11-30 20:40:02
【问题描述】:
Cliente insert_last_adq(int option,Viagem global,Cliente adq,Cliente esp,int data,char *destino,int cod_destino,int id,char *nome){
/*FIX: Caso quando full*/
Cliente new_node = (Cliente) malloc( sizeof(Clientes_node) );
Cliente adq_orig = adq;
Cliente esp_orig = esp;
new_node->data=data;
new_node->cod_destino=cod_destino;
new_node->id=id;
strcpy(new_node->destino,destino);
strcpy(new_node->nome,nome);
switch( option ){
    case 0:
        if(adq==NULL){
            new_node->next=NULL;
            if(option==0){
                diminuir_disp(global,data,cod_destino);
            }
            return new_node;
        } else if( get_viagens_disp_destino(global,data,cod_destino) > 0 ){
            while(adq->next!=NULL){
                adq=adq->next;
            }
            adq->next=new_node;
            new_node->next=NULL;
            diminuir_disp(global,data,cod_destino);
            return adq_orig;
        } else if( get_viagens_disp_destino(global,data,cod_destino)==0 ){
            /*FIX: Not workin*/
            if(esp==NULL){
                new_node->next=NULL;
                esp=new_node;
            }else{
                while(esp->next!=NULL){
                    esp=esp->next;
                }
                esp->next=new_node;
                new_node->next=NULL;
                return adq_orig;
            }
        }
        break;
    case 1:
        if(esp==NULL){
                new_node->next=NULL;
                return new_node;
            }else{
                while(esp->next!=NULL){
                    esp=esp->next;
                }
                esp->next=new_node;
                new_node->next=NULL;
                return esp_orig;
            }
        break;
}

}

在评论 FIX:不工作后,我有一行:

esp=new_node;

所以我的目标是给出链表的起始地址,尤其是 new_node 的地址。 我知道如果我返回一个地址,我可以更改它,但问题是 adq 链表将是接收返回值的那个。

顺便说一句,esp 和 adq 一样指向结构,因此不需要“*”。 并且 adq 和 esp 属于同一类型“Cliente”

【问题讨论】:

  • 不要在 typedef 后面隐藏指针性质,显然你正在使用类型 Cliente
  • 那我怎样才能将adq初始化为NULL呢?
  • 要“将adq初始化为NULL” --> Cliente_as_a_non_pointer_type *adq = NULL;
  • 不要转换从malloc()返回的结果。在C语言中不是必须的,可以隐藏包含所需函数原型的失败。

标签: c linked-list


【解决方案1】:

我只是在参数中添加了一个整数。我将它设置为 0 或 1,具体取决于我想将返回值设置为的 wut 列表。然后出我刚才用的函数:

if(out_int==0){
    adq=return_pCliente;
}else if(out_int==1){
    esp=return_pCliente;
}

out_int 作为 int *out_int 在函数的参数中传递,因此可以在函数内部进行更改。 其余代码无需更改。我正在上班,所以我的解决方案工作得很好。但是感谢您的帮助,学到了一两个新东西。

【讨论】: