您的位置:首页 > 编程语言 > Java开发

Java实现-两个链表的交叉

2017-06-06 09:58 393 查看


/**
* 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 A=headA;
ListNode B=headB;
int A_length=1;
while(A.next!=null){
A=A.next;
A_length++;
}
int B_length=1;
while(B.next!=null){
B=B.next;
B_length++;
}
if(A!=B){
return null;
}
ListNode short_list=headA;
ListNode long_list=headB;
if(A_length>B_length){
long_list=headA;
short_list=headB;
}
for(int i=0;i<Math.abs(A_length-B_length);i++){
long_list=long_list.next;
}
while(long_list!=null){
if(long_list==short_list){
return long_list;
}else{
long_list=long_list.next;
short_list=short_list.next;
}
}
return null;

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