[LeetCode] 141 - 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) {
    ListNode *n1, *n2;
    n1 = n2 = head;
    while (n1 != nullptr && n2 != nullptr) {
      n1 = n1->next;
      n2 = n2->next;
      if (n2) {
        n2 = n2->next;
      } else {
        return false;
      }
      if (n2 == n1) {
        return true;
      }
    }
    return false;
  }
};

 

posted on 2015-10-03 11:13  tuituji  阅读(111)  评论(0编辑  收藏  举报

导航