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?
这道题要用双指针,但我想试一下投机取巧的办法行不行,果然A了
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public boolean hasCycle(ListNode head) { 14 if(null == head) 15 return false; 16 ListNode point = head; 17 while(null != point){ 18 if(point.val != Integer.MIN_VALUE) 19 point.val = Integer.MIN_VALUE; 20 else 21 return true; 22 point = point.next; 23 } 24 return false; 25 } 26 }
双指针,一个走一步一个走两步,有环两个一定会相遇
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public boolean hasCycle(ListNode head) { 14 if(null == head) 15 return false; 16 ListNode slow = head; 17 ListNode fast = head; 18 while(fast != null && fast.next != null){ 19 slow = slow.next; 20 fast = fast.next.next; 21 if(slow == fast) 22 return true; 23 } 24 return false; 25 } 26 }