Intersection of Two Linked Lists

原创 2015年07月09日 11:16:51
/**
 * 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;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode-160-Intersection of Two Linked Lists

Intersection of Two Linked Lists Write a program to find the node at which the intersection of two...

Intersection of Two Linked Lists leetcode

Write a program to find the node at which the intersection of two singly linked lists begins. ...

Leetcode: Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins. F...

LeetCode (160) Intersection of Two Linked Lists

题目Write a program to find the node at which the intersection of two singly linked lists begins. For...

【Leetcode】:Intersection of Two Linked Lists

题目链接:https://oj.leetcode.com/problems/intersection-of-two-linked-lists/ 分析:题目就是求两个链表的的第一个交点,如果没有交点...

160. Intersection of Two Linked Lists

题目: Write a program to find the node at which the intersection of two singly linked lists begins. ...

[LeetCode]problem 160. Intersection of Two Linked Lists

TAG求两个无环链表第一个相交节点 题目链接方法MD智障啊。真是不服不行。编程之美上有一个基础的问题,只判断是否相交;然后后续有个问题就是如果需要找第一个相交节点该怎么办?当时我随便一想,觉得应该没有...

【leetcode 两个链表的交集点】Intersection of Two Linked Lists

leetcode上最新的面试题目,求两个链表的交集,难度为easy,附个人理解解析以及题目作者的英文解析。

Leetcode之Intersection of Two Linked Lists

leetcode之Intersection of Two Linked Lists分析,双指针

[LeetCode] Intersection of Two Linked Lists

Intersection of Two Linked Lists   Write a program to find the node at which the intersection ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)