首页 > 代码库 > LeetCode Linked List Cycle II
LeetCode Linked List Cycle II
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *detectCycle(ListNode *head) { ListNode* fast = head; ListNode* slow = head; while (step(fast, 2) && step(slow, 1)) { if (fast == slow) break; } if (fast == NULL) { return NULL; } ListNode* fake_end = slow; ListNode* h2 = fake_end->next; ListNode* h1 = head; ListNode* cur1 = h1; ListNode* cur2 = h2; int len1 = 0, len2 = 0; while (cur1 != fake_end) len1++, cur1 = cur1->next; while (cur2 != fake_end) len2++, cur2 = cur2->next; if (len1 == len2) { len1 = len2 = 0; } else if (len1 > len2) { len1 = len1 - len2; len2 = 0; } else { len1 = 0; len2 = len2 - len1; } step(h1, len1); step(h2, len2); while (h2 != h1 && step(h1, 1) && step(h2, 1)); return h1; } bool step(ListNode* &cur, int n) { while (cur != NULL && n > 0) { n--; cur = cur->next; } return n == 0; }};
求链表环和Y型链表交点的结合。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。