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 *one = head; ListNode *two = head; while (two && two->next) { one = one->next; two = two->next; two = two->next; if (one == two) return true; } return false; } };
原文地址:http://blog.csdn.net/elton_xiao/article/details/46332007