题目描述: 环形链表
给定一个链表,判断链表中否有环。
补充:
你是否可以不用额外空间解决此题?
解题思路:
一开始的代码只针对链表的头尾循环的特殊情况,没有考虑在中间成环,中间成环的没想出不用额外空间的方法,所以就直接加了判定循环次数然后过了。看了一下别人的代码思路,就是用两个指针,一个跑的快一个跑的慢,那么如果有环的话,跑的快的一定会追满的一圈。
代码:
/**
* 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) {
int n = 0;
while(head != NULL&&head->next != NULL) {
if(head->next == head) return true;
head->next = head->next->next;
if(n++ > 10000) return true;
}
return false;
}
};
/**
* 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,*fast=head;
while(fast&&fast->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast)return true;
}
return false;
}
};