LeetCode No.160 Intersection of Two Linked Lists | #Linked-list

Q:

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.
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.

A:

可以处理no intersection case。
没变要处理距离diff,没必要考虑value,没必要map/look up。

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {  
            return null;
        }
        
        ListNode p1 = headA;
        ListNode p2 = headB;

        while (p1 != null && p2 != null & p1 != p2){
            p1 = p1.next;
            p2 = p2.next;

            if (p1 == p2) return p1;  //即便no intersection,p1和p2也都已经指向null了

            if (p1 == null) p1 = headB;
            if (p2 == null) p2 = headA;
        }
        return p1;
}
}

最关键的思想:如果iteration了一整个ListNodes都reach到null了,那么使其指向另外一个List的head。如果没有intersection,(那么另外一个pointer reach到null的时候,也同样指向另外一个List的head,)最终,两个pointer都会遍历自己的ListNodes和对方List的ListNodes,所以会 同时 reach到对方最后的一个节点(null)。这个时候p1=p2, p1=null, p2=null

还有种写法(Java 问号表达式,三目运算):
p1 = ( p1 == null ? headB : p1.next ); p2 = ( p2 == null ? headA : p2.next );
a = b ? c : d 如果b的条件成立,赋值a = c, 否则 a = d。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容