上一节结束后,我们已经可以判断链表是否有环了,如果无环,那么按照前两节所讲的方法去判断链表是否相交以及获取相交结点,如果有环呢?怎么判断是否相交?
题目
给出俩个单向链表的头指针,比如 h1,h2,判断这俩个链表是否相交
解题步骤
/*判断结点是不是在链表上
head  链表头
node  结点
*/
bool ifNodeOnList(ListNode * head,ListNode * node){
	if(node==NULL)
		return 0;
	//为防止有环链表无限遍历,首先进行有无环判断
	ListNode * circleNode = ifCircle(head);
	int count = 0;//经过重复结点的次数
	while(head!=NULL&&count<2){
		if(head==node)
			return 1;
		if(head==circleNode)
			count++;
		head=head->nextNode;
	}
	return 0;
}
//判断有环链表是否相交
bool ifCircleListCross(ListNode * L1,ListNode * L2){
	ListNode * node = ifCircle(L1);
	if(node!=NULL)
		return ifNodeOnList(L2,node);
	return 0;
}#include <stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
/**
4.判断两个【有环】链表是否相交
思路
	判断一链表上俩指针相遇的那个节点,【在不在另一条链表上】。
	如果在,则相交,如果不在,则不相交。
*/
/**
链表结构体
*/
struct ListNode{
	int data;
	ListNode * nextNode;
	ListNode(ListNode * node,int value){
		nextNode=node;
		data=value;
	}
};
ListNode * L1;
ListNode * L2;
/**
判断链表是否有环
node  链表头指针
方法:用两个指针,一个指针步长为1,一个指针步长为2,若最后相遇,则链表有环
有环 返回两指针相遇位置
无环 返回NULL
*/
ListNode * ifCircle(ListNode * node){
	if(NULL==node)
		return false;
	ListNode * fast = node->nextNode;
	ListNode * slow = node;
	while(NULL!=fast&&NULL!=fast->nextNode){
		fast=fast->nextNode->nextNode;//步长为2
		slow=slow->nextNode;//步长为1
		if(fast==slow){
			cout<<"链表有环"<<endl;
			return fast;
		}
	}
	cout<<"链表无环"<<endl;
	return NULL;
}
/*判断结点是不是在链表上
head  链表头
node  结点
*/
bool ifNodeOnList(ListNode * head,ListNode * node){
	if(node==NULL)
		return 0;
	//为防止有环链表无限遍历,首先进行有无环判断
	ListNode * circleNode = ifCircle(head);
	int count = 0;//经过重复结点的次数
	while(head!=NULL&&count<2){
		if(head==node)
			return 1;
		if(head==circleNode)
			count++;
		head=head->nextNode;
	}
	return 0;
}
//判断有环链表是否相交
bool ifCircleListCross(ListNode * L1,ListNode * L2){
	ListNode * node = ifCircle(L1);
	if(node!=NULL)
		return ifNodeOnList(L2,node);
	return 0;
}
//创建有环链表
ListNode * createCircleList(){
	ListNode * node = new ListNode(NULL,0);
	ListNode * enter = node;
	node = new ListNode(node,1);
	node = new ListNode(node,2);
	enter->nextNode=node;
	node = new ListNode(node,3);
	node = new ListNode(node,4);
	return node;
}
//创建有环链表相交
void createCircleListCross(){
	L1 = new ListNode(NULL,0);
	ListNode * enter2 = L1;//L2的入口
	L1 = new ListNode(L1,1);
	L1 = new ListNode(L1,2);
	enter2->nextNode=L1;//L1的入口
	L1 = new ListNode(L1,3);
	L1 = new ListNode(L1,4);
	L2 = new ListNode(enter2,0);
	L2 = new ListNode(L2,1);
	L2 = new ListNode(L2,2);
}
//创建有环链表不相交
void createCircleListNotCross(){
	L1=createCircleList();
	L2=createCircleList();
}
void main()
{
	/*
	ListNode * node = createCircleList();
	ListNode * node2 = new ListNode(NULL,0);
	cout<<ifNodeOnList(node,node2)<<endl;
	*/
	//createCircleListNotCross();
	createCircleListCross();
	if(ifCircleListCross(L1,L2))
		cout<<"相交"<<endl;
	else
		cout<<"不相交"<<endl;
	system("pause");
}原文地址:http://blog.csdn.net/hzy38324/article/details/45305825