LeetCode-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?
runner 问题,注意while循环条件;
/**
* 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 || head.next == null || head.next.next == null){
return false;
}
ListNode fast = head;
ListNode slow = head;
while(fast !=null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
return false;
}
}
posted on 2015-03-18 06:15 IncredibleThings 阅读(143) 评论(0) 收藏 举报
浙公网安备 33010602011771号