算法小解:160. 相交链表

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

解:哈希集合,用集合存储其中一个链表的所有元素,遍历另一个链表的元素时查看集合中是否存在该元素,如果存在则相交。

/**
 * 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) {
        Set<ListNode> visited = new HashSet<ListNode>();
        ListNode temp = headA;
        while (temp != null) {
            visited.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while (temp != null) {
            if (visited.contains(temp)) {
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }
}

解:A链表和B链表长度分别为 a 和 b ,假设存在相交链表且这公共部分的长度为 c ,建立两个 potinerA 和 potinerB ,这两个指针都是一个时间单位移动一长度,同时移动,potinerA走完了A链表后走B链表当走到公共部分时走了 a + (b - c),同理potinerB走完了B链表走A链表当走到公共部分时走了 b + (a - c),由于 a + (b - c) = b + (a - c),同时走到了公共节点。如果不存在相交链表,c为0,他们会同时走到null值。

思路:Krahets

 

/**
 * 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) {
        /*
        * A链表长度为a,B链表长度存在b,假设存在公共部分长度为c
        * a + b - c = b + a - c,如果存在则会相交,如果不存在c为0,都会同时走向null值
         */
        ListNode potinerA = headA, potinerB = headB;
        while(potinerA != potinerB){
            potinerA = potinerA != null ? potinerA.next : headB;
            potinerB = potinerB != null ? potinerB.next : headA;
        }
        return potinerA;
    }
}
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值