算法面试100题——7.微软亚院之编程判断俩个链表是否相交

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

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值