Java implementation LeetCode 141 circular linked list

141. The circular linked list

Given a list, the list is determined whether a ring.

To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.

Example 1:

Input: head = [3,2,0, -4] , pos = 1
Output: true
explanation: the list has a ring tail portion connected to a second node.
Here Insert Picture Description

Example 2:

Input: head = [1,2], pos = 0
Output: true
explanation: the list has a ring, which is connected to the tail of the first node.
Here Insert Picture Description

Example 3:

Input: head = [1], pos = -1
Output: false
interpretation: the list does not ring.

Here Insert Picture Description

Advanced:

You can use O (1) (ie, constant) memory to solve this problem?

/**
 * 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;
        ListNode slow = head;
        while(fast != slow){
            if(fast.next == null || fast.next.next == null)   return false;
            fast = fast.next.next;
            slow = slow.next;
        }
        return true;
    }
}
Released 1262 original articles · won praise 10000 + · views 850 000 +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104434550