Question: 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?
Personal thoughts:
1. Determine whether a linked list has a ring. The standard practice is to take the speed pointer, one step, and two steps. When the fast pointer catches up with the slow pointer, it indicates that there is a ring.
2. Pay attention to several points. 1. The empty node linked list has no loops. 2. The two steps of the fast pointer are also step by step. Check every step.
Code:
1 #include <stddef.h> 2 3 struct ListNode 4 { 5 int val; 6 ListNode *next; 7 ListNode(int x) : val(x), next(NULL) {}; 8 }; 9 10 class Solution11 {12 public:13 bool hasCycle(ListNode *head)14 {15 if (!head)16 {17 return false;18 }19 20 ListNode *one = head;21 ListNode *two = head;22 23 while (true)24 {25 two = two->next;26 if (!two)27 {28 return false;29 }30 if (two == one)31 {32 return true;33 }34 two = two->next;35 if (!two)36 {37 return false;38 }39 if (two == one)40 {41 return true;42 }43 one = one->next; 44 }45 }46 };47 48 int main()49 {50 return 0;51 }
View code
This method is basically used on the Internet. The main problem is to consider special circumstances and boundary conditions.