找到两个单链表的交点

作者: Gressil | 来源:发表于2015-11-12 18:46 被阅读1224次

问题很简单,两个无环的单链表有个交点,找到这个点。不过题目要求不能用额外的空间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;
    }

相关文章

  • Day19

    Intersection of Two Linked Lists**思路:没有读懂题目的含义,找到两个单链表的交点...

  • Swift - LeetCode - 相交链表

    题目 相交链表 问题: 编写一个程序,找到两个单链表相交的起始节点。 示例: 说明: 如果两个链表没有交点,返回 ...

  • 相交链表

    相交链表 编写一个程序,找到两个单链表相交的起始节点。 注意: 如果两个链表没有交点,返回 null. 在返回结果...

  • 相交链表

    编写一个程序,找到两个单链表相交的起始节点。 注意: 如果两个链表没有交点,返回 null.在返回结果后,两个链表...

  • 160. 相交链表

    编写一个程序,找到两个单链表相交的起始节点。注意: 如果两个链表没有交点,返回 null.在返回结果后,两个链表仍...

  • 找到两个单链表的交点

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

  • 常见的算法题

    一、找两个链表的交点 存在集中特殊情况: 1、链表长度相同且没交点 2、链表长度相同有交点 3、长度不同有交点(最...

  • 经典面试题之链表

    《程序员面试金典》p49,2.6, 求单链表环路的入口结点。 相关题目:给定两个单链表,求他们的共同交点。解法:(...

  • leetcode 单链表的各种算法

    1 递归实现:合并两个有序的单链表 2 递归实现:单链表逆序存入vector 3 循环实现:快慢指针找到单链表中间...

  • 算法练习7:求两个单链表的相交点

    两个单链表,相交,会成为一个横躺的Y形状,求它们的交点 暴力解法 双层遍历,查看一个链表里是否有与另一个链表相同的...

网友评论

    本文标题:找到两个单链表的交点

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