新博文地址:[leetcode]Linked List Cycle
http://oj.leetcode.com/problems/linked-list-cycle/
这道题是很经典的面试题,在腾讯阿里笔试,网易面试中都遇到过原题。。。。双指针,不多说了
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Follow up:
Can you solve it without using extra space?
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode first = head;
ListNode second = head;
while (true) {
try {
first = first.next;
second = second.next.next;
} catch (NullPointerException e) {
return false;
}
if (first == second) {
return true;
}
}
}
两个指针,一个每次走一步,另一个每次走两步,如果存在环的话,肯定会遇到的,如果不存在环的话,往后走肯定会遇到空指针的。