Thursday, October 29, 2015

Leetcode: Linked List Cycle

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?

-----------------------------------------------------------------
-----------------------------------------------------------------
An interesting problem. 
Using two pointers: slow and fast. fast proceeds two nodes/step while slow one node/step. They will meet eventually if there is a loop inside. 
/////////////////////////////////////////////////////////////
//codes
class Solution {
public:
       bool hasCycle(ListNode *head) {
              //check input
              if (head == NULL || head->next == NULL)return false;
              //loop
              ListNode *slow = head, *fast = head;
              while (fast != NULL && fast->next != NULL){
                     fast = fast->next->next;
                     slow = slow->next;
                     if (fast == NULL)return false;
                     else if (fast == slow)return true;
              }
              return false;
       }
};

No comments:

Post a Comment