剑指Offer 37题 两个链表的第一个公共节点 Java版

package test;

public class GetFirstCommonNode {
	
	class ListNode{
		public String key;
		public ListNode next;
	}
	
	public ListNode findFirstCommonNode(ListNode headOne, ListNode headTwo){
		
		if(headOne == null || headTwo == null){
			return null;
		}
		
		int length1 = getListLength(headOne); 
		int length2 = getListLength(headTwo);
		
		int lenghtdif = length1 - length2;
		
		ListNode headLong = headOne;
		ListNode headShort = headTwo;
		
		if(length2 > length1){
			headLong = headTwo;
			headShort = headOne;
			lenghtdif = length2 - length1;
		}
		
		for(int i=0; i<lenghtdif; ++i){
			headLong = headLong.next;
		}
		
		while((headLong!=null)&&(headShort!=null)&&(headLong!=headShort)){
			headLong = headLong.next;
			headShort = headShort.next;
		}
		
		ListNode firstCommonNode = headLong;
		
		return firstCommonNode;
	}
	
	
	
	
	public int getListLength(ListNode head){
		int length = 0;
		ListNode node = head;
		while(node!=null){
			++length;
			node = node.next;
		}
		return length;
	}
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GetFirstCommonNode node = new GetFirstCommonNode();
		
		ListNode a = node.new ListNode();
		a.key = "a";
		ListNode b = node.new ListNode();
		b.key = "b";
		ListNode e = node.new ListNode();
		e.key = "e";
		ListNode d = node.new ListNode();
		d.key = "d";
		ListNode f = node.new ListNode();
		f.key = "f";
		ListNode h = node.new ListNode();
		h.key = "h";
		
		f.next = d;
		d.next = b;
		b.next = a;
		h.next = e;
		e.next = b;
		b.next = a;
		ListNode node1 = node.findFirstCommonNode(f, h);
		System.out.println(node1.key);
		

	}

}
另外书上还提到,还有蛮力法和用两个栈的方法,没事的时候可以练练手。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值