1。 判断两个链表是否有环,
如果都没有,判断最后一个节点是不是一样的。
如果一个有,一个没有,不相交。
如果都有,判断环上的一点是否在另一个单链表里。
#include <iostream>
using namespace std;
typedef struct stNode
{
int ch;
struct stNode *pNext;
stNode(){ch = 0; pNext = NULL;}
}Node;
void createList( Node &head)
{
int i = 0;
Node *p = &head;
for (; i < 10; i++)
{
p->pNext = new Node();
p->pNext->ch = i;
p = p->pNext;
}
}
void printList( const Node &head)
{
int i = 0;
int times = 0;
const Node *tmp = head.pNext;
while (tmp)
{
times++;
cout << i++ << ": " << tmp->ch << endl;
if ( times == 50)
{
break;
}
tmp = tmp->pNext;
}
}
void createCrossList(Node &head)
{
int i = 13;
int crossPos = 4;
Node *tmp;
Node *p = &head;
for ( ; i > 0; i--)
{
p->pNext = new Node();
p->pNext->ch = i;
if (i == crossPos)
{
tmp = p->pNext;
}
p = p->pNext;
}
p->pNext = tmp;
}
void desdoryCrossList(Node &head, Node &joinNode)
{
Node *p = head.pNext;
Node *curN = p;
int i = 0;
while(curN)
{
if (curN == &joinNode)
{
i++;
if(i == 2)
{
break;
}
}
p = curN->pNext;
cout << "delete " << curN->ch << endl;
delete curN;
curN = p;
}
}
bool hasLoop(Node &head, Node *&a_meet, int &slowWork)
{
Node *slow, *fast;
slow = fast = &head;
while (fast)
{
slow = slow->pNext;
slowWork++;
fast = fast->pNext;
if (fast)
{
fast = fast->pNext;
}
else
{
return false;
}
if (slow == fast)
{
a_meet = slow;
return true;
}
}
return false;
}
Node * getJoinNode(Node &head, Node &MeetNode)
{
Node *p1 = &head;
Node *p2 = &MeetNode;
while (p1 != p2)
{
p1 = p1->pNext;
p2 = p2->pNext;
}
return p1;
}
int main()
{
Node head ;
head.ch = 100;
//createList(head);
createCrossList(head);
int len = 0;
Node *p = NULL;
if (hasLoop(head, p, len))
{
cout << "has loop" << endl;
}
else
{
cout << "do not has loop" << endl;
}
//printList(head);
cout << "The value when meeting: " << p->ch << endl;
Node *p1 = NULL;
int LoopLen = 0;
hasLoop(*p, p1, LoopLen);
cout << "loop len:" << LoopLen << endl;
p1 = getJoinNode(head, *p);
cout << "Join in :" << p1->ch << endl;
desdoryCrossList(head, *p1);
return 0;
}