c或c ++

时间:2015-08-18 05:38:45

标签: c++ c linked-list

我正在尝试交叉两个链表但我在使用<>比较两个列表的两个数据时遇到了一些问题。

 if(t2->data < t1->data)
    t2 = t2->next;  
    if(t2->data > t1->data)
    t1 = t1->next;

代码停止执行。但是,当我评论这些代码时,它可以工作并提供输出

struct node *getIntersection (struct node *head1, struct node *head2)
    {
        struct node *result = NULL;
        struct node *t1 = head1;
        struct node *t2 = head1;

        while (t1 != NULL && t2 != NULL)
        {
            if (t2->data==t1->data){
                push (&result, t1->data);
                t1=t1->next;
                t2=t2->next;

            }
            if(t2->data < t1->data)
            t2 = t2->next;  
            if(t2->data > t1->data)
            t1 = t1->next;
        }

        return result;
    }

1 个答案:

答案 0 :(得分:2)

这里试试这个:

 struct node *getIntersection (struct node *head1, struct node *head2)
 {
    struct node *result = NULL;
    struct node *t1 = head1;
    struct node *t2 = head1;

    while (t1 != NULL && t2 != NULL)
    {
        if (t2->data==t1->data){
            push (&result, t1->data);
            t1=t1->next;
            t2=t2->next;

        }
        if(t1 != NULL && t2 != NULL){
        if(t2->data < t1->data)
        t2 = t2->next;  }

        if(t2 !=NULL){
        if(t2->data > t1->data)
        t1 = t1->next;}
    }

    return result;
}

我想问题是你没有验证下一个t1或t2,如果它是NULL,程序将停止执行是正常的