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;
        
    }
}

 

相关文章:

  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2021-05-18
  • 2021-04-23
  • 2021-09-02
猜你喜欢
  • 2021-09-27
  • 2022-01-31
  • 2021-11-14
  • 2021-10-23
  • 2021-11-13
  • 2021-07-16
  • 2021-11-22
相关资源
相似解决方案