【问题标题】:Linked List in c or c++c 或 c++ 中的链表
【发布时间】:2015-11-10 21:53:19
【问题描述】:

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

 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;
    }

【问题讨论】:

  • 在第二个 if 之前检查 t2-&gt;next != NULL
  • 嗯,明白了。谢谢你:)
  • 您打算将t1t2 都设置为指向同一个列表?

标签: c++ c linked-list


【解决方案1】:

这里试试这个:

 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,程序会停止执行是正常的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2015-05-06
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多