1.1数组和链表:160. Intersection of Two Linked Lists(Leetcode)

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

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.

 题目大意:给定两个链表的头节点,找出两个链表相交的节点,若没有相交节点则返回null;

先贴代码:

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null)
            return null;
        //新建对象存储A,B链的末尾节点
        ListNode tailA = null;
        ListNode tailB = null;
        //新建对象指向A,B链头节点
        ListNode pA = headA;
        ListNode pB = headB;
        
        while(true){
            //若遍历到链末尾,则重新从另一头开始遍历
            if(pA == null){
                pA = headB;
                
            }
            if(pB == null){
                pB = headA;
            }
            //确定末尾节点位置
            if(pA.next == null){
                tailA = pA;
            }
            if(pB.next == null){
                tailB = pB;
            }
            //如果没有相同末尾的话,则说明没有交点
            if(tailA != null && tailB != null && tailA != tailB)
                return null;
            if(pA == pB)
                return pA;//如果在任何地方相遇,则此节点便是相交节点
            pA = pA.next;
            pB = pB.next;
        }
            
    }
先提一种容易想到的方法,也是博主第一时间想到的方法:

第一次遍历获得两个链表的长度,然后重新回到起点,将长的链表前移”长度差“个单位后同时遍历,每次都比较是否相等。

上述方法是在Solution里面见到的,从时间或空间复杂度来讲,两者没有明显差距,但是第二种看起来连贯且高大上,大意就是两边同时开始遍历,遍历到末尾时判断末尾节点是否相同从而判断交点是否存在,然后交换链表头继续遍历,若任何时刻两节点相等,则此节点即为解。

思路:要解决的就是长度差的问题,假设有节点,两链表长度差即为相交前的长度差,遍历速度相等的情况下,两个遍历指针同时将长短链表长度不同的地方各走一遍,即路程相等。最后得一定会同时在相交点相遇。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值