题目描述:
给定一个链表,判断链表中是否有环。
示例:
思路:
判断链表中是否有环,在这里用快慢指针法,假设慢指针 one 每次向后走一步,快指针 two 每次向后走两步;当链表为空或者链表只有一个结点的时候,显然没有环,然后快指针 two 向后先走一步,此时判断 one 和 two 是否相同,若相同,返回true,即链表有环;若不同 one 和 two 一次向后走一步,此时 one 走了一步,two 走了两步;若在循环条件(two != null && two.next!=null)成立时,一直进行循环,否则,跳出循环,返回false,即链表没有环
代码:
**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode one = head;
ListNode two = head;
while(two != null && two.next!=null){
two = two.next;
if(one == two){
return true;
}
one = one.next;
two = two.next;
}
return false;
}
}