【力扣 简单 C】160. 相交链表

目录

题目

解法一:哈希

解法二:双指针


题目

【力扣 简单 C】160. 相交链表_第1张图片

解法一:哈希

struct node
{
    struct ListNode* val;
    struct node* next;
};
 
struct hashSet
{
    struct node** bucket;
    int size;
};
 
struct hashSet* hashSetInit(int size)
{
    struct hashSet* hashSet = malloc(sizeof(*hashSet));
    hashSet->bucket = calloc(size, sizeof(*hashSet->bucket));
    hashSet->size = size;
    return hashSet;
}
 
long long hash(struct hashSet* hashSet, struct ListNode* val)
{
    return ((long long)val >> 7) % hashSet->size;
}
 
void hashSetInsert(struct hashSet* hashSet, struct ListNode* val)
{
    long long index = hash(hashSet, val);
    struct node* newNode = malloc(sizeof(*newNode));
    newNode->val = val;
    newNode->next = hashSet->bucket[index];
    hashSet->bucket[index] = newNode;
}
 
bool hashSetFind(struct hashSet* hashSet, struct ListNode* val)
{
    long long index = hash(hashSet, val);
    struct node* curNode = hashSet->bucket[index];
    while (curNode)
    {
        if (curNode->val == val)
            return true;
        curNode = curNode->next;
    }
    return false;
}
 
void hashSetFree(struct hashSet* hashSet)
{
    for (int i = 0; i < hashSet->size; i++)
    {
        struct node* freeNode = hashSet->bucket[i];
        while (freeNode)
        {
            struct node* nextNode = freeNode->next;
            free(freeNode);
            freeNode = nextNode;
        }
    }
    free(hashSet->bucket);
    free(hashSet);
}
 
struct ListNode* find(struct ListNode* head1, struct ListNode* head2)
{
    struct hashSet* hashSet = hashSetInit(512);
    struct ListNode* list1CurNode = head1;
    struct ListNode* list2CurNode = head2;
 
    while (list1CurNode)
    {
        hashSetInsert(hashSet, list1CurNode);
        list1CurNode = list1CurNode->next;
    }
 
    while (list2CurNode)
    {
        if (hashSetFind(hashSet, list2CurNode))
            break;
        list2CurNode = list2CurNode->next;
    }
    hashSetFree(hashSet);
    return list2CurNode;
}
 
struct ListNode* getIntersectionNode(struct ListNode* headA, struct ListNode* headB)
{
    return find(headA, headB);
}

解法二:双指针

struct ListNode* find(struct ListNode* head1, struct ListNode* head2)
{
    struct ListNode* list1CurNode = head1;
    struct ListNode* list2CurNode = head2;
    while (list1CurNode != list2CurNode)
    {
        list1CurNode = list1CurNode ? list1CurNode->next : head2;
        list2CurNode = list2CurNode ? list2CurNode->next : head1;
    }
    return list1CurNode;
}

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
    return find(headA, headB);
}

你可能感兴趣的:(力扣,C,c语言,leetcode,数据结构,算法,开发语言)