Skip to content

Latest commit

 

History

History
executable file
·
30 lines (20 loc) · 628 Bytes

File metadata and controls

executable file
·
30 lines (20 loc) · 628 Bytes

160. 相交链表

https://leetcode-cn.com/problems/intersection-of-two-linked-lists

Solution

Java

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    if(headA == null || headB == null) {
        return null;
    }

    ListNode nodeA = headA;
    ListNode nodeB = headB;
    while(nodeA != nodeB) {
        nodeA = nodeA == null ? headB : nodeA.next;
        nodeB = nodeB == null ? headA : nodeB.next;
    }

    return nodeA;
}

Tip

  • 定义两个指针,第一轮让两个到达末尾的节点指向另一个节点的头部,继续遍历,如果相遇则为交点。