【Leetcode】Linked List Cycle

来源:互联网 发布:程序员找工作 编辑:程序博客网 时间:2024/06/16 02:13

原题链接:https://leetcode.com/problems/linked-list-cycle/

题目:

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

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

思路:

两个指针,一个移动一步,一个移动两步,所以两个指针相对距离每移动一次就加一,如果有循环,一定可以在 循环长度/(2-1) 个循环后相遇,没有循环则会遇到null

算法:

[java] view plain copy
  1. public boolean hasCycle(ListNode head) {  
  2.     ListNode q = head, p = null;// p走两步,q走一步  
  3.     if (q == null || q.next == null) {// 单结点无循环时  
  4.         return false;  
  5.     }  
  6.     p = q.next.next;  
  7.     while (p != null) {  
  8.         if (q == p) {  
  9.             return true;  
  10.         }  
  11.         if (p.next == null) {// p走两步,要判断p.next为空  
  12.             return false;  
  13.         }  
  14.         p = p.next.next;  
  15.         q = q.next;  
  16.     }  
  17.     return false;  
  18. }  
0 0
原创粉丝点击