运用快慢指针判断链表是否有环

时间:2022-12-22 10:17:41

例题可以参见LeetCode中的 Linked list circle  http://oj.leetcode.com/problems/linked-list-cycle/

解题思路就是运用快慢指针来判断链表中是否有环

让慢指针一次走一步,快指针一次走两步,如果链表中含有环,快的指针会再次和慢的指针相遇。

/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
// use fast pointer & slow pointer,judge whether Linkedlist has a circle
//fast pointer foot two once; slow pointer foot one step once
//if Linkedlist has a circle ,fast will came across slow
public class Solution {
public boolean hasCycle(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ListNode slow = head;
ListNode fast = head;
//fast==null in case empty Linkedlist
//fast.next.next!=null,make sure list is not our border
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
return true;
}
return false;
}
}
  //fast==null 是空链表的情况
  //否则就是fast遍历到结束的标志,为了防止fast.next.next出界,先确保fast.next不是链表的尾