当前位置: 代码迷 >> 综合 >> LeetCode | Intersection of Two Linked Lists
  详细解决方案

LeetCode | Intersection of Two Linked Lists

热度:7   发布时间:2023-12-22 05:41:50.0

https://leetcode.com/problems/intersection-of-two-linked-lists/

将其中一条链表首尾相接,然后对另外一条链表进行环路检测。如果两个链表相交,那么另外一条链表就是带环链表,否则无环。问题转化为linked list cycle II了。

记得最后将链表复原。

C++

class Solution { public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {if (!headA || !headB) return NULL;ListNode *tailB = headB;while (tailB->next) tailB = tailB->next;tailB->next = headB;ListNode *ret = detect_cycle(headA);tailB->next = NULL;return ret;}ListNode *detect_cycle(ListNode *head) {bool is_cycle = false;ListNode *slow = head, *fast = head;while (fast && fast->next) {slow = slow->next;fast = fast->next->next;if (slow == fast) { is_cycle = true; break; }}if (!is_cycle) return NULL;ListNode *start = head;while (start != slow) {slow = slow->next;start = start->next;}return start;} };

转载于:https://www.cnblogs.com/ilovezyg/p/6389098.html

  相关解决方案