小程序 - 链表检测环/链表是否交叉 等
Posted brayden
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了小程序 - 链表检测环/链表是否交叉 等相关的知识,希望对你有一定的参考价值。
链表检测环
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; }
以上是关于小程序 - 链表检测环/链表是否交叉 等的主要内容,如果未能解决你的问题,请参考以下文章