0
点赞
收藏
分享

微信扫一扫

剑指 Offer 52. 两个链表的第一个公共节点

陆佃 2021-09-21 阅读 28
今日算法
题目描述:
示例 1:

示例 2:

示例 3:

思路一:
代码实现:
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
         Map<ListNode, Integer> map = new HashMap();
         ListNode curOne = headA;
         while (curOne != null) {
             map.put(curOne, curOne.val);
             curOne = curOne.next;
         }
         ListNode curTwo = headB;
         Integer result = null;
         while (curTwo != null) {
             result = map.get(curTwo);
             if (result != null) {
                 return curTwo;
             }
             curTwo = curTwo.next;
         }
         return curTwo;
    }
}
思路二:
代码实现:
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode one = headA, two = headB;
        if (one == null || two == null) {
            return null;
        }
        while (one != two) {
            one = one == null ? headB : one.next;
            two = two == null ? headA : two.next;
        }
        return one;
    }
}
举报

相关推荐

0 条评论