判断两个链表是否相交

问题:

给出两个单向链表的头指针,比如h1、h2,判断链表是否相交,如果不相交返回NULL;如果相交,返回指向第一个相交节点的指针。时间复杂度控制在O(n)。

分析:

如果两单向链表相交的话,一定是Y型相交,不可能出现X型,弄清楚这点后接下来的工作就是:
(1)先找到h1,h2的最后一个节点L1和L2,同时记录节点数量a,b;(这里假设 a > b)
(2)判断最后一个节点是否相同;
如果不相同则没相交;
如果相同,则从第一个节点 (短链表) 和 第 |a-b|+1个节点 (长链表)开始比较 (这样,两个链表的指针到相交点的距离是一样的),看是否相等,不相等就寻找下一个节点直到找到交叉点。

代码如下:

class Node {
	char value;
	Node next;
}
Node intersect(Node h1, Node h2) {
	// l1 and l2 refer to the last nodes in the two lists.
	// a and b refer to the length of the lists.
	Node l1 = h1;
	int a = 1;
	
	Node l2 = h2;
	int b = 1;
	
	while (l1.next != null) {
		l1 = l1.next;
		a++;
	}
	
	while (l2.next != null) {
		l2 = l2.next;
		b++;
	} 
	// no intersection
	if (l1 != l2) {
		return null;
	} 
	//move the pointer of the longer list.
	for (int i = 0; i < Math.abs(a - b); i++) {
		if (a > b) {			
			h1 = h1.next;
		} else {
			h2 = h2.next;
		}	
	}
	
	while (h1 != h2) {
		h1 = h1.next;
		h2 = h2.next;
	}
	
	return h1;
} 

参考:http://blog.csdn.net/yysdsyl/article/details/1851505

转载请注明出处:http://blog.csdn.net/beiyeqingteng

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值