标签:

int CheckCross(pLinkList list1, pLinkList list2) //判断链表是否相交
{
assert(list1);
assert(list2);
pLinkNode cur1 = list1->pHead;
pLinkNode cur2 = list2->pHead;
if ((NULL==list1->pHead)||(NULL==list2->pHead))
{
return -1;
}
while (NULL!=cur1->next)
{
cur1 = cur1->next;
}
while(NULL!=cur2->next)
{
cur2 = cur2->next;
}
if (cur1 == cur2)
{
return 1; //相交
}
else
{
return -1; //不相交
}
}pLinkList Merge(pLinkList list1, pLinkList list2) //合并两个有序链表
{
assert(list1);
assert(list2);
if ((NULL == list1->pHead)&&(NULL == list2->pHead)) //考虑特殊情况
{
return NULL;
}
else if (NULL == list1->pHead)
{
return list2;
}
else if(NULL == list2->pHead)
{
return list1;
}
pLinkNode last = NULL;
pLinkNode newHead = NULL; //虚拟头结点
if (list1->pHead->data <list2->pHead->data) //把对第一个结点特殊处理
{
newHead= list1->pHead;
list1->pHead = list1->pHead->next;
}
else
{
newHead = list2->pHead;
list2->pHead = list2->pHead->next;
}
last=newHead; //让last指向虚拟结点链表的尾部
while ((NULL!= list1->pHead)&&(NULL!= list2->pHead))
{
if (list1->pHead->data <list2->pHead->data)
{
last->next = list1->pHead;
list1->pHead = list1->pHead->next;
}
else
{
last ->next= list2->pHead;
list2->pHead = list2->pHead->next;
}
last = last->next;
}
if (NULL == list1->pHead) //将集合中剩下的元素链接到last之后
{
last->next = list2->pHead;
}
else
{
last->next = list1->pHead;
}
list1->pHead = newHead;
return list1;
}pLinkNode CheckCycle(pLinkList list) //判断是否带环,若带环则返回相遇位置
{
assert(list);
pLinkNode fast = list->pHead; //快指针
pLinkNode slow = list->pHead; //慢指针
if (NULL==list->pHead)
{
return NULL;
}
while (fast!= NULL)
{
if (NULL != fast->next)
{
fast = fast->next->next;
slow = slow->next;
}
else
{
break;
}
if (fast == slow) //快慢指针相遇则有环
{
return slow;
}
}
return NULL; //没环则返回NULL
}int GetCircleLength(pLinkNode meet) //若链表带环这返回环的长度
{
assert(meet);
pLinkNode cur = meet->next;
int count = 1;
while (cur!=meet)
{
count++;
cur = cur->next;
}
return count;
}pLinkNode GetCycleEntryNode(pLinkList list, pLinkNode meet) //查找环的入口
{
assert(list);
pLinkNode link = list->pHead; //link指向链表的头
pLinkNode cycle = meet; //cycle指向链表的相遇点
while (link != cycle)
{
link = link->next;
cycle = cycle->next;
}
return link;
}标签:
原文地址:http://blog.csdn.net/lf_2016/article/details/51627967