两个链表的第一个公共结点

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(){

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值