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) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode cur1 = headA;
        ListNode cur2 = headB;
        int len1 = 1, len2 = 1;
        while (cur1.next != null) {
            cur1 = cur1.next;
            len1++;
        }
        while (cur2.next != null) {
            cur2 = cur2.next;
            len2++;
        }
        cur1 = headA;
        cur2 = headB;
        if (len1 > len2) {
            for (int i = 0; i < len1 - len2; i++) {
                cur1 = cur1.next;
            }
        } else {
            for (int i = 0; i < len2 - len1; i++) {
                cur2 = cur2.next;
            }
        }
        while (cur1 != null && cur2 != null) {
            if (cur1 == cur2) {
                return cur1;
            }
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        return null;
    }
}

阅读更多
文章标签: Linked List
个人分类: Leetcode 刷题
上一篇Reverse Bits
下一篇Power of Two
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭