141. Linked List Cycle(快慢指针---判断链表是否有环)
141. 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?
利用快慢指针,如果相遇则证明有环
注意边界条件: 如果只有一个node.
1 class Solution { 2 public: 3 bool hasCycle(ListNode *head) { 4 ListNode* slow = head; 5 ListNode* fast = head; 6 while(slow != NULL && fast != NULL && fast->next != NULL) { 7 slow = slow->next; 8 fast = fast->next->next; 9 if (slow == fast) return true; 10 } 11 return false; 12 } 13 };
1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 if(head==null || head.next==null) return false; 4 ListNode slower =head,faster = head; 5 while(faster!=null && faster.next!=null){ 6 if(faster==slower) return true; 7 faster = faster.next.next; 8 slower = slower.next; 9 } 10 return false; 11 } 12 }