题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:
正常的遍历,使用HashSet来判断是否重复
代码:
public boolean hasCycle(ListNode head) { HashSet hashFlag = new HashSet(); while(head!= null){ if(!hashFlag.add(head)){ return true; } head = head.next; } return false; }
思路二:采用快指针和慢指针
两个指针,移动的速度差一,所以快指针必定会“追上”慢指针。有点类似小学时候的追击问题
代码:
public boolean hasCycle(ListNode head) { ListNode Fast = head; ListNode Slow = head; while(Slow!= null){ if(Slow.next!= null && Fast.next!= null && Fast.next.next!= null){ Slow = Slow.next; Fast = Fast.next.next; if(Slow == Fast){ return true; } } else{ return false; } } return false; }
222