1、题目:给出俩个单向链表的头指针,比如h1,h2,判断这俩个链表是否相交。
为了简化问题,我们假设俩个链表均不带环。
2、知识点:链表、排序
3、思路:将指向结点的指针排序,排序后判断指针是否相交。排序复杂度为O(NlogN),判断相交的复杂度为O(M+N)。
/*用途:
**说明:
**算法:复制结点指针,排序
*/
//#define LOCAL
#include <cstdio>
#include <cstdlib>
#include <functional>
using namespace std;
#define MAXN 100
struct Node{
int data;
Node* next;
};
typedef Node* LinkList;
Node* NewNode();
Node* NewNode(int val);
Node* GetCross(LinkList head1, LinkList head2);
int CmpPNode(const void* a, const void* b);
int main()
{
#ifdef LOCAL
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
#endif
// printf("%d\n", sizeof(Node*));
// printf("%d\n", sizeof(Node));
LinkList head1 = NewNode();
Node* n1 = NewNode(1);
head1->next = n1;
Node* n2 = NewNode(2);
n1->next = n2;
Node* n3 = NewNode(3);
n2->next = n3;
Node* n4 = NewNode(4);
n3->next = n4;
Node* n5 = NewNode(5);
n4->next = n5;
LinkList head2 = NewNode();
Node* n6 = NewNode(9);
head2->next = n6;
Node* n7 = NewNode(8);
n6->next = n7;
n7->next = n3;
printf("%p\n", n2->next);
printf("%p\n", n7->next);
Node* cr = GetCross(head1, head2);
if(cr)
printf("%d", cr->data);
return 0;
}
Node* NewNode()
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = 0;
node->next = NULL;
}
Node* NewNode(int val)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = val;
node->next = NULL;
}
Node* GetCross(LinkList head1, LinkList head2)
{
if(head1->next==NULL || head2->next==NULL)
return NULL;
int arr1Len=0, arr2Len = 0;
Node* arr1[MAXN];
Node* arr2[MAXN];
while(head1->next || head2->next){
if(head1->next){
arr1[arr1Len++] = head1->next;
head1 = head1->next;
}
if(head2->next){
arr2[arr2Len++] = head2->next;
head2 = head2->next;
}
}
qsort(arr1, arr1Len, sizeof(Node*), CmpPNode);
qsort(arr2, arr2Len, sizeof(Node*), CmpPNode);
for(int i=0, j=0; i<arr1Len && j<arr2Len;){
if(arr1[i] == arr2[j])
return arr1[i];
else if(arr1[i] < arr2[j])
i++;
else
j++;
}
return NULL;
}
int CmpPNode(const void* a, const void* b)
{
return *(Node**)a - *(Node**)b;
}

本文介绍了一种判断两个单向链表是否相交的方法。通过复制链表节点指针并进行排序,最后比较两个已排序的链表来找出交点。此方法适用于不含环的链表,提供了一个实用的C语言实现示例。
653

被折叠的 条评论
为什么被折叠?



