题目: 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 *slow = head;
ListNode *fast = head;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
if(fast == slow){
return true;
}
}
return false;
}
};
转载请注明原文地址: https://ju.6miu.com/read-10380.html