Monday, May 4, 2015

Linked List Cycle

来源:Leetcode

原帖:http://oj.leetcode.com/problems/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?

代码:
 /**  
  * 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 || !head->next) return false;  
         ListNode *slow = head;  
         ListNode *fast = head->next;  
         while (true) {  
             if (fast == slow) return true;  
             if (!fast || !fast->next) return false;  
             fast = fast->next->next;  
             slow = slow->next;  
         }  
     }  
 };  

No comments:

Post a Comment