160 intersection of 2 linked lists

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

/**
 * 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 curA = headA;
        ListNode curB = headB;
        while (curA != curB) {
            if (curA == null) {
                curA = headB;
                //记得是用else,不然设成headB又会往下跑
            } else {
                curA = curA.next;
            }
            if (curB == null) {
                curB = headA;
            } else {
                curB = curB.next;
            }
            
        }
        return curA;
    }
}
A demonstration of intersection

如图中所示,curA和curB分别走完a + c + b和b + c + a之后会相遇在intersection处,因此让curA走完a和c之后放到headB走一遍b,让curB走完b和c之后放在headA之后走一遍a他们就会相遇

Last updated