链表检测环
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; }
时间: 2024-10-01 02:49:52