标签:
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==NULL || head->next==NULL){ return false; } ListNode *first =head; ListNode *second = head; while(first && second) { first = first->next; second = second->next; if(second){ second = second->next; } if(first==second){ return true; } } return false; } };
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
[Linked List]Linked List Cycle,Linked List Cycle II
标签:
原文地址:http://www.cnblogs.com/zengzy/p/5041012.html