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

来源:互联网 发布:淘宝详情图尺寸是多少 编辑:程序博客网 时间:2024/06/07 13:36
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里面见到的,从时间或空间复杂度来讲,两者没有明显差距,但是第二种看起来连贯且高大上,大意就是两边同时开始遍历,遍历到末尾时判断末尾节点是否相同从而判断交点是否存在,然后交换链表头继续遍历,若任何时刻两节点相等,则此节点即为解。

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

原创粉丝点击