leetcode 141 环形链表

     leetCode141题:判断一个给定的链表是否有环。

     解题思路:链表类的题,很多都可以使用快慢指针来解决,本题也可以使用快慢指针,如果有环,那么最后快慢指针指向的元素必定相同。

     代码如下

/**
 * 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) {
        if(head == null || head.next == null){
            return false;
        }
        ListNode fast = head.next.next;
        ListNode slow = head.next;
        while(fast != null && slow != null){
            if(fast == slow){
                return true;
            }
            if(fast.next == null){
                return false;
            }

            fast = fast.next.next;
            slow = slow.next;
        }
        return false;
    }
}

你可能感兴趣的:(leetcode,链表,算法)