【发布时间】: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->next != NULL。 -
嗯,明白了。谢谢你:)
-
您打算将
t1和t2都设置为指向同一个列表?
标签: c++ c linked-list