1. 程式人生 > >[leetcode]141. Linked List Cycle判斷鏈表是否有環

[leetcode]141. Linked List Cycle判斷鏈表是否有環

code AC LV class you return In CA .com

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

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

題意:

給定一個鏈表,判斷是否有環

思路:

快慢指針

若有環,則快慢指針一定會在某個節點相遇(此處省略證明)

技術分享圖片

代碼:

 1 public class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         ListNode fast = head;
 4         ListNode slow = head;
5 while(fast != null && fast.next != null){ 6 fast = fast.next.next; 7 slow = slow.next; 8 if(fast == slow) return true; 9 } 10 return false; 11 } 12 }

[leetcode]141. Linked List Cycle判斷鏈表是否有環