美文网首页
160. 相交链表

160. 相交链表

作者: 衣锦昼行 | 来源:发表于2019-08-07 15:30 被阅读0次

    编写一个程序,找到两个单链表相交的起始节点。
    输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
    输出:Reference of the node with value = 8
    输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

    注意:
    如果两个链表没有交点,返回 null.
    在返回结果后,两个链表仍须保持原有的结构。
    可假定整个链表结构中没有循环。
    程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。

    题解:题目意思不难理解,关键就在于

    /**
     * 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)
                return null;
            if(headB == null)
                return null;
           if(headA == headB)
               return headA;
            int lenA = 0,lenB = 0;
            ListNode nodeA = headA;
            ListNode nodeB = headB;
            while (nodeA != null){
                lenA++;
                nodeA = nodeA.next;
            }
            while (nodeB != null){
                lenB++;
                nodeB = nodeB.next;
            }
             nodeA = headA;
            nodeB = headB;
            if(lenA > lenB){
                int len = lenA - lenB;
                while (len>0){
                    len--;
                    nodeA = nodeA.next;
                }
            }
            else if(lenA < lenB){
                int len = lenB - lenA;
                while (len>0){
                    len--;
                    nodeB = nodeB.next;
                }
            }
            while (nodeA != null){
                if(nodeA == nodeB)
                    return nodeA;
                nodeA = nodeA.next;
                nodeB = nodeB.next;
            }
            return null;
        }
    }
    

    相关文章

      网友评论

          本文标题:160. 相交链表

          本文链接:https://www.haomeiwen.com/subject/hhoodctx.html