目錄
LeetCode-141題
LeetCode-141題
給定一個鏈表的頭節點,判斷鏈表中是否存在環
class Solution {public boolean hasCycle(ListNode head) {// checkif (head == null || head.next == null)return false;// 定義兩個指針,一個快指針[fast],一個慢指針[slow],并且它們開始都指向頭節點ListNode fast = head;ListNode slow = head;// fast指針一次前進兩個節點,slow指針一次前進一個節點while (fast.next != null && fast.next.next != null) {fast = fast.next.next;slow = slow.next;// 如果fast和slow能相遇,鏈表存在環if (fast == slow) {return true;}}// 不能相遇,則鏈表不存在環return false;}private static class ListNode {int val;ListNode next;public ListNode() {}public ListNode(int val) {this.val = val;}public ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
}