1.Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution{
public:
    bool hasCycle(ListNode* head){
        if(head==nullptr || head->next == nullptr) return false;
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }
};

2.Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

/**
 * 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){
        if(head == nullptr || head->next == nullptr) return nullptr;
        ListNode* slow = head;
        ListNode* fast = head;

        ListNode* crossNode = nullptr;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast){
                crossNode = slow;
                break;
            }
        }
        if(crossNode == nullptr){
            return nullptr;
        }else{
            slow = head;
            while(slow != crossNode){
                slow = slow->next;
                crossNode = crossNode->next;
            }
            return crossNode;
        }
    }
};

 

相关文章:

  • 2022-12-23
  • 2021-10-27
  • 2021-06-13
猜你喜欢
  • 2021-11-14
  • 2022-12-23
  • 2021-07-13
  • 2022-12-23
  • 2022-12-23
  • 2021-12-23
  • 2022-01-05
相关资源
相似解决方案