[LeetCode]160. Intersection of Two Linked Lists

来源:互联网 发布:pdf转jpg软件 编辑:程序博客网 时间:2024/05/21 06:27

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

找到第一个相同的节点


让长的链表的指针先移动差值距离,然后同时移动,判断是否当前节点相同

public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        int sizeA = 0;        int sizeB = 0;        ListNode curA = headA;        ListNode curB = headB;        while (curA != null) {            sizeA++;            curA = curA.next;        }        while (curB != null) {            sizeB++;            curB = curB.next;        }        while (sizeA > sizeB) {            headA = headA.next;            sizeA--;        }        while (sizeA < sizeB) {            headB = headB.next;            sizeB--;        }        while (headA != headB) {            headA = headA.next;            headB = headB.next;        }        return headA;    }}


0 0