您的位置:首页 > 其它

lintcode-medium-Intersetion of Two Linked Lists

2016-03-23 09:01 423 查看
Write a program to find the node at which the intersection of two singly linked lists begins.

The following two linked lists:

A:          a1 → a2
↘
c1 → c2 → c3
↗
B:     b1 → b2 → b3

begin to intersect at node c1.

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
/**
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// Write your code here

if(headA == null || headB == null)
return null;

ListNode p1 = headA;
ListNode p2 = headB;

int len1 = 0;
int len2 = 0;

while(p1 != null){
len1++;
p1 = p1.next;
}

while(p2 != null){
len2++;
p2 = p2.next;
}

p1 = headA;
p2 = headB;

if(len1 > len2){
for(int i = 0; i < len1 - len2; i++)
p1 = p1.next;
}
else if(len2 > len1){
for(int i = 0; i < len2 - len1; i++)
p2 = p2.next;
}

while(p1 != null && p2 != null && p1 != p2){
p1 = p1.next;
p2 = p2.next;
}

return p1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: