美文网首页
LintCode题解 | 爱彼迎面试真题:两个链表的交叉

LintCode题解 | 爱彼迎面试真题:两个链表的交叉

作者: SunnyZhao2019 | 来源:发表于2020-02-13 19:07 被阅读0次

【题目描述】
请写一个程序,找到两个单链表最开始的交叉节点。

1.如果两个链表没有交叉,返回null。
2.在返回结果后,两个链表仍须保持原有的结构。
3.可假定整个链表结构中没有循环。

【题目样例】

样例 1:

输入:
A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3
输出:c1
解释:在节点 c1 开始交叉。

样例 2:

输入:
Intersected at 6
1->2->3->4->5->6->7->8->9->10->11->12->13->null
6->7->8->9->10->11->12->13->null
输出: Intersected at 6
解释:begin to intersect at node 6.

【评测与题解】

→戳这里在线评测及查看题解

/**
* 本参考程序来自九章算法,由 @九章算法 提供。版权所有,转发请注明出处。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
* - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
* - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
*/ 

public class Solution {
    /**
     * @param headA: the first list
     * @param headB: the second list
     * @return: a ListNode 
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        
        // get the tail of list A.
        ListNode node = headA;
        while (node.next != null) {
            node = node.next;
        }
        node.next = headB;
        ListNode result = listCycleII(headA);
        node.next = null;
        return result;
    }
    
    private ListNode listCycleII(ListNode head) {
        ListNode slow = head, fast = head.next;
        
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return null;
            }
            
            slow = slow.next;
            fast = fast.next.next;
        }
        
        slow = head;
        fast = fast.next;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        
        return slow;
    }
}

相关文章

网友评论

      本文标题:LintCode题解 | 爱彼迎面试真题:两个链表的交叉

      本文链接:https://www.haomeiwen.com/subject/grvlfhtx.html