160. 相交链表

题目

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

如下面的两个链表:
输入: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 个节点。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

一开始就想到了暴力破解,双重循环。但是没有去实现。看了下题解,可以用hash表,也可以用双指针。
双指针的解法,真的是今年遇到最烂漫的解法。我沿着你走过的路终将相遇
如果两个链表有交集,必然相遇。

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode a = headA;
        ListNode b = headB;
        if(headA == null || headB == null){
            return null;
        }
        while(a != b){
            if(a!=null){
                a = a.next;
            }else{
                a = headB;
            }
            if(b!=null){
                b = b.next;
            }else{
                b = headA;
            }
        }
        return a;

        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容