LeetCode第160题--相交链表

编写一个程序,找到两个单链表相交的起始节点。

示例 1:
在这里插入图片描述输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *pLeft = headA;
        ListNode *pRight = headB;
        vector<ListNode *> vecNode;
        while(pLeft)
        {
            vecNode.push_back(pLeft);
            pLeft = pLeft->next;
        }
        while(pRight)
        {
            if(find(vecNode.begin(), vecNode.end(), pRight) != vecNode.end())
            {
                return pRight;
            }
            pRight = pRight->next;
        }
        return NULL;
    }
};

一种采用投机取巧的办法,使用vector存储其中一条链表,利用find函数找出相交点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(NULL == headA || NULL == headB) return NULL;
        ListNode *pHeadA = headA;
        ListNode *pHeadB = headB;
        ListNode *pTailB = headB;
        while(pTailB->next)
        {
            pTailB = pTailB->next;
        }
        pTailB->next = pHeadB;
        
        ListNode *fast = headA;
        ListNode *slow = headA;
        while(fast->next && fast->next->next)
        {
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow)
            {
                fast = pHeadA;
                while(fast != slow)
                {
                    fast = fast->next;
                    slow = slow->next;
                }
                pTailB->next = NULL;
                return fast;
            }
        }
        pTailB->next = NULL;
        return NULL;
    }
};

先使链表成环,利用环形链表的特征找出入环位置(即为相交点),最后链表还原。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值