题目描述
https://leetcode-cn.com/problems/linked-list-cycle/
思路题解
只遍历一次,当head
不为空时,循环遍历。当head的值不等于100009
时,设为100009
,相当于做了标记。当相等时代表已经遍历过了,退出循环,返回true
。若遍历完了还没返回,则返回false
,代表没有环。
代码如下:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
for head!=nil{
if head.Val!=100009{
head.Val=100009
head=head.Next
}else{
return true
}
}
return false
}