找到两个单链表的交点

问题很简单,两个无环的单链表有个交点,找到这个点。不过题目要求不能用额外的空间O(1),并且是线型时间O(n)。

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→c1 → c2 → c3
begin to intersect at node c1.

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.

这个问题我没有按要求作出来,我只能想到O(n^2)的暴力比较,或者用一个Stack的额外空间O(n)。于是看看了别人家孩子的代码。思路非常巧妙,和判断单链表有没有环的解法一样,「双指针同时遍历两个链表,到结尾之后跳到另一个链表的头继续遍历」代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public ListNode getIntersection(ListNode headA, ListNode headB) {
     if (headA == null || headB == null) return null;
        ListNode node1 = headA;
        ListNode node2 = headB;
        while (node1 != node2) {
            node1 = node1.next;
            node2 = node2.next;
            if (node1 == node2) return node1; // in case node1 == node2 == null
            if (node1 == null) node1 = headB;//这里可能会错,不要写成node1=node2
            if (node2 == null) node2 = headA;
        }
        return node1;
    }

你可能感兴趣的:(找到两个单链表的交点)