用c语言从另一个链表中填充空链表

时间:2015-01-25 18:07:52

标签: c list linked-list

我有一个包含数据的完整链表,我想要的是用相同的数据填充另一个链表但有条件,所以让我们说这是链表:

char cl; 
int time; 
int lng;
  

C 0 1

     

D 0 2

     

B 2 1

     

A 2 2

我想从这个列表复制到一个新的空列表,但仅限于(时间> 0),所以新的列表将是这样的:

  

B 2 1

     

A 2 2

我试过这段代码,但它不起作用:

void insert(const node * n )// this where i put the pointer of the full node
{
    node *head=n;
    node *sec; // new node
    sec=(node*)malloc(sizeof(node)); 

    do{
        if(head->time>0){
            strcpy(sec->cl,head->cl);
            sec->time= head->time;
            sec->lng= head->lng;
            head=head->next;
            sec=sec->next;
        }
        else 
            head=head->next;
    }while(head!=NULL);
    print(sec) // this will print the new node
}

请帮帮我。谢谢

2 个答案:

答案 0 :(得分:2)

我结合了评论中的所有建议以及一些其他修复。  以下是生成的代码:

const node* insert(const node * head)
{
    node *sec = NULL;  // start of the new, second list
    node *last = NULL; // points to the last inserted node

    while(head!=NULL){
        if(head->time > 0){
            node* newsec=(node*)malloc(sizeof(node)); 
            newsec->cl = head->cl;
            newsec->time = head->time;
            newsec->lng = head->lng;
            newsec->next = NULL;
            //Add the new node to the list:
            if(last == NULL){ //This is the first element in the new list
               sec = newsec;
            }else{
               last-> next = newsec;
            }
            last = newsec;
        }
        head=head->next;
    }
    print(sec); // this will print the new node
    return sec;
}

你的错误:

  • 错误的内存分配(您只分配了一次内存)
  • 不需要strcpy(字符串不需要字符串副本)
  • while必须位于循环的开头(如果给定列表为空,则代码将失败)
  • 缺少分号
  • 新列表的错误连接
  • 错误的const-correctness(node *head=n;中缺少const)
  • 内部head - 变量不是必需的(并且参数命名n也不理想。如果您将其命名为" start" /" head&# 34; /"开始",评论不是必要的)

另一个建议:为结构使用大写名称,因为它可以更容易区分类型和变量(应该是Node,而不是node)

请注意,您可能希望从返回值类型中删除const

答案 1 :(得分:-1)

// Note: a better function name might be: printNodesWithTime

void insert(const node * pOld )
{

    // note: since nothing is done with the new linked list,
    //       there is no need to actually create it

    while( NULL != pOld )
    {

        if(pPld->time > 0)
        {
            print(pOld) // this will print the node
        }

        // step to next old node
        pOld = pOld->next;

    } // end while
} // end function: insert