关闭

Intersection of Two Linked Lists

标签: Linked List
116人阅读 评论(0) 收藏 举报
分类:
/**
 * 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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:25916次
    • 积分:2340
    • 等级:
    • 排名:第15896名
    • 原创:214篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条