http://oj.leetcode.com/problems/linked-list-cycle/
检验一个链表是否有环,题目唯一的要求是 without using extra space!
思路是,给节点的val赋一个特殊的值来表明节点已经被遍历过。
/**
* 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) {
while(1) {
if(head == NULL) break;
if(head->val == 11111111) return true;
head->val = 11111111;
head = head->next;
}
return false;
}
};