链表交叉

#include <iostream>
using namespace std;
typedef struct ListNode
{
int data;
ListNode *next;
}Node;
void print(ListNode *head)
{
while (head)
{
cout << head->data;
head = head->next;
}
return;
}
Node* list_cross(Node *head1, Node *head2)
{
int len1 = 0, len2 = 0;
Node *cur1 = head1;
Node *cur2 = head2;
while (cur1->next != NULL)
{
len1++;
cur1 = cur1->next;
}
while (cur2->next != NULL)
{
len2++;
cur2 = cur2->next;
}
if (cur1 != cur2)
return NULL;
cur1 = head1;
cur2 = head2;
if (len1 > len2)
{
for (int i = 0; i < len1 - len2; i++)
{
cur1 = cur1->next;
}
}
if (len1 < len2)
{
for (int i = 0; i < len2 - len1; i++)
{
cur2 = cur2->next;
}
}
while (cur1 != NULL && cur2 != NULL && cur1 != cur2)
{

cur1 = cur1->next;
cur2 = cur2->next;
}
return cur1;
}
int main()
{
//int len1=0, len2=0;
Node p5{ 5, NULL };
Node p4{ 4, &p5 };
Node p3{ 3, &p4 };
Node p2{ 2, &p3 };
Node p1{ 1, &p2 };
Node *head1 = &p1;
print(head1);
cout << endl;
Node p9{ 9, &p3 };
Node p8{ 8, &p9 };
Node p7{ 7, &p8 };
Node *head2 = &p7;
print(head2);
cout << endl;
Node *result = list_cross(head1, head2);
if (result!=NULL)
cout << result->data;
system("pause");
return 0;

}


猜你喜欢

转载自blog.csdn.net/qq_38665104/article/details/80398237