Intersection of Two Linked Lists 找出2个链表的交点

来源:互联网 发布:目的论 知乎 编辑:程序博客网 时间:2024/05/19 22:25

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.
限制:O ( n )的时间复杂度 和 O ( 1 ) 的空间复杂度。
如图链表A 和 B 的长度是不一样的。
要是A 还在a1出发,B在b2出发,大家走的步数一样,就可以一起到达c1了。
一种方法是分别计算链表A 和 链表 B的长度,lenA, lenB ,谁长,谁先出发 abs ( lenB - lenA )步。
运行时间:

代码:
public class IntersectionofTwoLinkedLists {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        int lenA = listLength(headA);        int lenB = listLength(headB);        ListNode curA = headA, curB = headB;        int diff = lenA - lenB;        while (diff > 0) {            curA = curA.next;            diff--;        }        while (diff < 0) {            curB = curB.next;            diff++;        }        while (curA != null && curB != null) {            if (curA == curB) {                return curA;            }            curA = curA.next;            curB = curB.next;        }        return null;    }    private int listLength(ListNode head) {        int count = 0;        while (head != null) {            head = head.next;            count++;        }        return count;    }}

另外一种是比较巧妙的:
大家都走lenA + lenB步。
代码:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {    //boundary check    if(headA == null || headB == null) return null;    ListNode a = headA;    ListNode b = headB;    //if a & b have different len, then we will stop the loop after second iteration    while( a != b){        //for the end of first iteration, we just reset the pointer to the head of another linkedlist        a = a == null? headB : a.next;        b = b == null? headA : b.next;        }    return a;}
参考:
https://leetcode.com/discuss/66203/java-solution-without-knowing-the-difference-in-len

1 0
原创粉丝点击