[Leetcode]141. Linked List Cycle

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode]141. 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?

 

思路:快慢指针,设置一个走两步的快指针,和一个走一步的慢指针,如果有环,则它们一定会相遇。

 

 1 /**
 2  * Definition for singly-linked list.
 3  * class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public boolean hasCycle(ListNode head) {
14         if (head==null)
15             return false;
16         ListNode p1 = head,p2 = head.next;
17         while (p2!=null){
18             p2 = p2.next;
19             if (p2==null)
20                 return false;
21             p2 = p2.next;
22             p1 = p1.next;
23             if (p2==p1)
24                 return true;
25         }
26         return false;
27     }
28 }

 


以上是关于[Leetcode]141. Linked List Cycle的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-141. Linked List Cycle

leetcode 141. Linked List Cycle

LeetCode 141. Linked List Cycle

LeetCode 141 Linked List Cycle

[Leetcode]141. Linked List Cycle

LeetCode 141, 142. Linked List Cycle I+II