题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
上午终于把数组的题目全部都刷完了,接下来开始看链表的题目。第一道题很简单,就是判断一个链表中是否存在环。我们知道,如果一个链表中没有环,那么我们在遍历的过程中最后一个元素会指向空地址。但是如果单纯的使用遍历法,当存在环的时候,会进入死循环==所以要想办法结局这个问题。我们可以在遍历过程中将每个元素都指向head,这样如果不存在环,就会有空指针,如果存在环,最终会指向head而结束。代码如下所示:
public boolean hasCycle1(ListNode head) {
if(head == null || head.next == null) {
return false;
}
ListNode node = head;
while(node != null) {
if(node.next == head) {
return true;
}
ListNode temp = node.next;
node.next = head;
node = temp;
}
return false;
}
还有一种方法是使用两个指针,一个fast,一个slow。这样如果存在环最终而这回相等,如果不存在环,就会空指针。代码入下:
public boolean hasCycle(ListNode head) {
ListNode fast=head, slow=head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
return true;
}
return false;
}