題目鏈接: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?
經典(用爛了)的追及問題。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) {
return false;
}
ListNode p1 = head, p2 = head.next;
while(p1 != null && p2 != null) {
if(p1 == p2) {
return true;
} else {
// p1走一步
p1 = p1.next;
if (p2.next == null) {
return false;
} else {
// p2走兩步
p2 = p2.next.next;
}
}
}
return false;
}
}
ps:很久沒刷題了,每天做一做,健康又益智^^。