leetcode解题

This commit is contained in:
wu xiangkai
2025-10-22 16:35:11 +08:00
parent 75c4bd8473
commit 7bbd47f65f
3 changed files with 107 additions and 0 deletions

View 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