题目:判断两个链表是否相交
分析:如果被问道此问题,一定要分两种情况回答,第一种是链表不存在环,第二种就是存在环的情况
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