getIntersectionNode 解题报告

来源:互联网 发布:mac flv 编辑:程序博客网 时间:2024/05/21 07:54

getIntersectionNode

Description

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

Notice

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.

Example

The following two linked lists:

A:          a1 → a2                   ↘                     c1 → c2 → c3                   ↗            B:     b1 → b2 → b3

begin to intersect at node c1.

Challenge

Your code should preferably run in O(n) time and use only O(1) memory.

实现思路

一旦两个链表出现相交,可以确定的是,从相交点往后,两个链表的长度是一样的,要找到相交点,我们可以先分别求出两个链表的长度,然后让长的先往前走几步,使两个链表剩下的长度一致,然后就可以两条同时向前遍历并进行比较节点是否相等,一旦出现相等,即为开始相交的节点,如果遍历完还没有出现相等,则说明两个链表不相交
在整个求解过程中,local和global的第i项只和第i-1项有关,所以我们可以简化local、global成两个数,具体实现如下所示:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null;       *     } * } */public class Solution {    /**     * @param headA: the first list     * @param headB: the second list     * @return: a ListNode      */    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        // Write your code here        if (headA == null || headB == null) {            return null;        }        int length1 = 1, length2 = 1;        ListNode head1 = headA, head2 = headB;        while (head1.next != null && head2.next != null) {            head1 = head1.next;            head2 = head2.next;            length1++;        }        length2 = length1;        while (head1 != null) {            head1 = head1.next;            length1++;        }        while (head2 != null) {            head2 = head2.next;            length2++;        }        while (length1 > length2) {            headA = headA.next;            length1--;        }        while (length2 > length1) {            headB = headB.next;            length2--;        }        while (headA != null && headB != null && headA != headB) {            headA = headA.next;            headB = headB.next;        }        if (headA != null && headB != null && headA == headB) {            return headA;        }        return null;    }}
0 0
原创粉丝点击