package java_study.JianZhiOffer;
import org.junit.Test;
/**
* Created by ethan on 2015/7/7.
* 剑指offer No37 两个链表的第一个公共结点
* 两个思路:1.压栈 2.数出每个链表的长度,并让长链表先走相差的步数。
* 这里实现的是思路2, 没有经过测试
*/
public class No37两个链表的第一个公共结点 {
public Node findFirstCommonNode(Node head1, Node head2){
if (head1==null || head2==null) return null;
int count_1 = 0;
int count_2 = 0;
Node tmp1 = head1;
Node tmp2 = head2;
while (tmp1 != null){
tmp1 = tmp1.getNext();
count_1++;
}
while (tmp2 != null){
tmp2 = tmp2.getNext();
count_2++;
}
int gap = count_1-count_2;
if (gap<0){
for (int i=0; i>gap; i--){
head2 = head2.getNext();
}
}else if(gap>0){
for (int i=0; i<gap; i++){
head1 = head1.getNext();
}
}
while (head1!=null){
if (head1==head2)
break;
else {
head1 = head1.getNext();
head2 = head2.getNext();
}
}
return head1;
}
@Test
public void test(){
}
}
两个链表的第一个公共结点
最新推荐文章于 2023-11-24 15:57:52 发布