1. 程式人生 > >getIntersectionNode 解題報告

getIntersectionNode 解題報告

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; } }