第12题 判断两个链表是否相交

题目:判断两个链表是否相交


分析:如果被问道此问题,一定要分两种情况回答,第一种是链表不存在环,第二种就是存在环的情况


1. 先判断带不带环

2. 如果都不带环,就判断尾节点是否相等

3. 如果都带环,判断一链表上俩指针相遇的那个节点,在不在另一条链表,如果在,则相交,如果不在,则不相交


struct node {
	int data;
	struct node* next;
}

//判断带不带环
//如果无环,返回0,赋值lastNode
//如果有环返回1,赋值circleNode
int isCircle(struct node* head, struct node** circleNode, struct node** lastNode) {
	struct node* fast = head->next;
	struct node* slow = head;

	while(fast != slow && fast && slow) {
		if(fast->next != NULL)
			fast = fast->next;
		if(fast->next == NULL)
			lastNode = &fast;
		if(slow->next == NULL)
			lastNode = &slow;
		
		fast = fast->next;
		slow = slow->next;
	}

	if(fast == slow && fast && slow) {
		circleNode = &fast;
		return 1;
	}
	else {
		return 0;
	}


}

//返回0,表示没有相交
//返回1,表示两个链表相交
int detect(struct node* h1, struct node* h2) {
	struct node* circleNode1;
	struct node* circleNode2;
	struct node* lastNode1;
	struct node* lastNode2;

	int isCircle1 = isCircle(h1, &circleNode1, &lastNode1);
	int isCircle2 = isCircle(h2, &circleNode2, &lastNode2);

	//一个有环,一个无环
	if(isCircle1 != isCircle2)
		return 0;
	//两个都无环,判断最后一个节点是否相等
	else if(!isCircle1 && !isCircle2)
		return (lastNode1 == lastNode2 ? 1 : 0);
	//两个都有环,判断环里的节点能否到达另一个链表里的节点
	else {
		struct node* temp = circleNode1->next;
		while(temp != circleNode1) {
			if(temp == circleNode2)
				return 1;
			temp = temp->next;
		}
		return 0;
	}

	return 0;
}

本文参考: http://blog.csdn.net/v_JULY_v/article/details/6447013

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值