面试题7:判断链表是否有环,返回环的入口点
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; } } };