Intersection of Two Linked Lists

来源:互联网 发布:ubuntu根目录空间不足 编辑:程序博客网 时间:2024/05/16 11:16

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.
这道题也参考了下思路, 主要的问题在于怎么转化成linked list cycle问题,如果两个链表有公共部分,那么将两个链表链接起来以后会形成环, 这样就可以根据上一题的思路来解。
但是要注意将链表恢复。这个思路要再梳理一下。

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if(headA == null || headB == null){            return null;        }        ListNode pointer = headA;        ListNode breakPoint;        while(pointer.next != null){            pointer = pointer.next;        }        breakPoint = pointer;        pointer.next = headB;        ListNode slow = headA;        ListNode fast = headA;        while(fast.next!=null && fast.next.next != null){            fast = fast.next.next;            slow  = slow.next;            if(fast == slow){                //根据公式,快指针到重合点的举例==head到重合点的距离                slow = headA;                while(slow!= fast){                    slow = slow.next;                    fast = fast.next;                }                breakPoint.next = null;                return slow;            }        }        breakPoint.next = null;        return null;    }





sdfsd

0 0
原创粉丝点击