Linked List Cycle
Description
Given a linked list, determine if it has a cycle in it.
Example Given -21->10->4->5, tail connects to node index 1, return true
Challenge:
Follow up:
Can you solve it without using extra space?We are here
Link
Method
- x
- x
Example
- 1
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: True if it has a cycle, or false */ bool hasCycle(ListNode *head) { // write your code here if (!head) { return false; } ListNode* slow = head; ListNode* fast = head->next; while (fast && fast->next) { if (slow == fast) { return true; } slow = slow->next; fast = fast->next->next; } return false; } };
Similar problems
x
Tags
x