Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目要求判断链表是否有环形,题目不难,方法很巧,典型的双指针问题,一开始现实判断最简单的空链表或者只有一个节点但是无环的情况,接下来设置一快一慢两个指针,快指针每次比慢指针夺走一步,倘若无环,快指针一定会先到达null指针位置;如果有环,那么最后快指针一定会追上慢指针
代码如下:
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 bool hasCycle(ListNode *head) {
12 if (!head || !head->next)
13 return false;
14 ListNode *slow = head;
15 ListNode *fast = head->next;
16 while (slow != fast)
17 {
18 if (fast->next == nullptr || fast->next->next == nullptr)
19 return false;
20 slow = slow->next;
21 fast = fast->next->next;
22 }
23 return true;
24 }
25 };