美文网首页
160. Intersection of Two Linked

160. Intersection of Two Linked

作者: namelessEcho | 来源:发表于2017-09-09 17:22 被阅读0次

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

    For example, the following two linked lists:

    A: a1 → a2

    c1 → c2 → c3

    B: b1 → b2 → b3
    begin to intersect at node c1.

    要求两个表之间的交。 思路是先计算出两个链表的长度,在较长的链表上前进两个链表长度的差,那么当短链表的头和长链表的头共同前进时,如果存在交的话一定会相遇。这里要注意一定要从两个不同的头来分配,注意这样的分配是错的:

    ListNode longer = lenA>lenB ? headA: headB;
    ListNode shorter =LenA<lenB? headA: headB;
    

    当lenA==lenB时,明显地,longer和shorter都指向了headA;

    正确的写法可以是:

    ListNode longer =   lenA>lenB ? headA: headB;
    ListNode shorter = longer==headB? headA: headB;
    

    Notes:

    If the two linked lists have no intersection at all, return null.
    The linked lists must retain their original structure after the function returns.
    You may assume there are no cycles anywhere in the entire linked structure.
    Your code should preferably run in O(n) time and use only O(1) memory.

    /**
     * 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;
            int lenA = length(headA);
            int lenB = length(headB);
            int count = lenB>lenA?lenB-lenA:lenA-lenB;
            ListNode longer = lenA>lenB ? headA: headB;
            ListNode shorter = longer==headA? headB: headA;
            // two pointer must point to two differrne starts ;
            for(int i = 1 ;i<=count ;i++)
            {
                longer=longer.next;
            }
            while(longer!=shorter)
            {
                longer=longer.next;
                shorter=shorter.next;
            }
            return longer ;
        }
        private int length  (ListNode head) 
        {
            int result = 0 ;
            while(head!=null)
            {
                head=head.next;
                result++;
            }
            return result;
        }
    }
    

    相关文章

      网友评论

          本文标题:160. Intersection of Two Linked

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