Linked List Cycle II(C++环形链表 II)

男娘i 2023-01-23 13:56 11阅读 0赞

(1)快慢指针

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode *detectCycle(ListNode *head) {
  12. ListNode *slow=head,*fast=head;
  13. while(fast!=nullptr) {
  14. slow=slow->next;
  15. if(fast->next==nullptr) return nullptr;
  16. fast=fast->next->next;
  17. if(slow==fast) {
  18. ListNode* temp=head;
  19. while(temp!=slow) {
  20. temp=temp->next;
  21. slow=slow->next;
  22. }
  23. return temp;
  24. }
  25. }
  26. return nullptr;
  27. }
  28. };

发表评论

表情:
评论列表 (有 0 条评论,11人围观)

还没有评论,来说两句吧...

相关阅读