Intersection of Two Linked Lists

来源:互联网 发布:公有云计算基础架构 编辑:程序博客网 时间:2024/05/14 08:49
/** * 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;    }}

0 0
原创粉丝点击