141. Linked List Cycle
/** * 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; } // fast slow pointers ListNode fast = head; ListNode slow = head; while(fast.next != null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; if(fast == slow){ return true; } } return false; } }
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
posted on 2018-07-18 09:28 猪猪🐷 阅读(61) 评论(0) 收藏 举报
浙公网安备 33010602011771号