leetcode解题
This commit is contained in:
41
141.linked-list-cycle.java
Normal file
41
141.linked-list-cycle.java
Normal file
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* @lc app=leetcode id=141 lang=java
|
||||
*
|
||||
* [141] Linked List Cycle
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* class ListNode {
|
||||
* int val;
|
||||
* ListNode next;
|
||||
* ListNode(int x) {
|
||||
* val = x;
|
||||
* next = null;
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
public class Solution {
|
||||
/**
|
||||
* 快慢指针,若链表中存在环,则快指针一次动两步,慢指针一次动一步,快指针一定会赶上慢指针
|
||||
*
|
||||
* @param head
|
||||
* @return
|
||||
*/
|
||||
public boolean hasCycle(ListNode head) {
|
||||
ListNode slow = head, fast = head;
|
||||
boolean isCycle = false;
|
||||
while(fast != null && fast.next != null) {
|
||||
fast = fast.next.next;
|
||||
slow = slow.next;
|
||||
if(fast == slow) {
|
||||
isCycle = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return isCycle;
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
Reference in New Issue
Block a user