LeetCode: Linked List Cycle
题目链接: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:很久没刷题了,每天做一做,健康又益智^^。
版权所有,转载请注明出处
http://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/