LeetCode——Linked List Cycle

Description:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

在不借助辅助空间的情况下判断一个链表是否存在回路。

可以用两个指针,一个从头节点开始,一个从头节点的next节点开始,node1一次走一步,node2一次走两步,这样一来如果链表存在回路的话,这两个节点就会相遇。否则则不存在回路。

/**
 * 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) {
            return false;
        }
        
        ListNode node1 = head, node2 = head.next;
        
        while(node1 != null && node2 != null && node2.next != null) {
            if(node1 == node2) {
                return true;
            }
            node1 = node1.next;
            node2 = node2.next.next;
        }
        
        return false;
        
    }
}
原文地址:https://www.cnblogs.com/wxisme/p/4844538.html