Leetcode学习笔记:#160. Intersection of Two Linked Lists

    xiaoxiao2025-02-09  18

    Leetcode学习笔记:#160. Intersection of Two Linked Lists

    Write a program to find the node at which the intersection of two singly linked lists begins.

    实现

    public ListNode getIntersectionNode(ListNode headA, ListNode headB){ if(headA == null || headB == null) return null; ListNode a = headA; ListNode b = headB; while(a != b){ a = a == null ? headB : a.next; b = b == null ? headA : b.next; } return a; }

    思路: 假设A的长度为a+c,B的长度为b+c,交换之后,A要move多b+c次,B要move多a+c次,所以c为多长不需知道。A和B最终一定会在 a + c + b (b + c + a)相遇。

    最新回复(0)