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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null || headB==null) return null;
int l1 = findLen(headA);
int l2 = findLen(headB);
if(l1>l2) {
return findNode(headB, headA, l2, l1);
}else {
return findNode(headA, headB, l1, l2);
}
}
private ListNode findNode(ListNode headA, ListNode headB, int l1, int l2) {
int gap = l2 - l1;
ListNode p1 = headA;
ListNode p2 = headB;
while(gap>0) {
p2 = p2.next;
gap--;
}
while(p1!=null) {
if(p1==p2) return p1;
else {
p1 = p1.next;
p2 = p2.next;
}
}
return null;
}
private int findLen(ListNode node) {
if(node==null) return 0;
ListNode p = node;
int l1 = 0;
while(p!=null) {
p = p.next;
l1 ++;
}
return l1;
}
}
==========
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode node1 = headA;
ListNode node2 = headB;
while (node1 != node2) {
node1 = node1.next;
node2 = node2.next;
if (node1 == node2) return node1; // in case node1 == node2 == null
if (node1 == null) node1 = headB;
if (node2 == null) node2 = headA;
}
return node1;
}
}
没有评论:
发表评论