【LeetCode】141. 环形链表

【题目描述】

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。


示例 2:

输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。


示例 3:

输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle

【解题思路】

快慢指针技巧:

通过使用具有 不同速度 的快、慢两个指针遍历链表。慢指针每次移动一步,而快指针每次移动两步。

如果链表中不存在环,最终快指针将会最先到达尾部,此时我们可以返回 false。

如果链表中存在环,则快指针和慢指针最终会相遇,即快指针等于慢指针,此时我们返回true。

【提交代码】

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 bool hasCycle(struct ListNode *head) {
 9     struct ListNode *fast;
10     struct ListNode *slow;
11 
12     if( head == NULL || head->next == NULL )
13         return false;
14 
15     fast = head->next;
16     slow = head;
17     while( fast != slow )
18     {
19         if( fast == NULL || fast->next == NULL )
20             return false;
21 
22         fast = fast->next->next;
23         slow = slow->next;
24     }
25 
26     return true;
27 }
原文地址:https://www.cnblogs.com/utank/p/13231669.html