您的位置:首页 > 移动开发 > 微信开发

小程序 - 链表检测环/链表是否交叉 等

2016-03-31 00:03 525 查看
链表检测环

int cycleExists(Node *head)
{
Node *fast, *slow;
if (head == NULL)
return 0;
for (slow = head, fast = head->next; fast && fast->next;
fast = fast->next->next, slow = slow->next)
if (slow == fast)
return 1;
return 0;
}


链表是否交叉

int listOverlapped(Node *list1, Node *list2)
{
if (!list1 || !list2)
return 0;
for (; list1->next; list1 = list1->next);
for (; list2->next; list2 = list2->next);
return list1 == list2;
}


两个链表第一个公共节点

Node* firstCommonNode(Node *list1, Node *list2)
{
int num1, num2;
Node *n1, *n2;
if (!list1 || !list2)
return NULL;
for (num1 = 0, n1 = list1; n1->next; num1++, n1 = n1->next);
for (num2 = 0, n2 = list2; n2->next; num2++, n2 = n2->next);
if (n1 != n2)
return NULL;
if (num1 > num2)
for (num1 -= num2; num1 > 0; num1--, list1 = list1->next);
else
for (num2 -= num1; num2 > 0; num2--, list2 = list2->next);
for (; list1 != list2; list1 = list1->next, list2 = list2->next);
return list1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: