目录
一,题目描述
英文描述
中文描述
二,解题思路
三,AC代码
C++
Java
四,解题过程
第一博
一,题目描述
英文描述
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
中文描述
给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
进阶:
你能用 O(1)(即,常量)内存解决此问题吗?
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二,解题思路
首先有以下几个直观的事实:
- 1,如果一个链表是循环链表,由于链表的唯一指向性,那么一个指针在前进过程中必定会进入一个循环,即永远不会指向空指针;
- 2,当两个指针以不同的速度进入循环后,会成为一个追及问题(假设指针静止,快指针以速度差向前运动,快指针必定可以追上慢指针)。从离散的角度来看,速度相差为一时,快指针必定可以和慢指针位置重合;
以上便是快慢指针算法。
三,AC代码
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL || head->next == NULL) return false;
ListNode *slow = head, *fast = head->next;
while(fast->next != NULL && fast->next->next != NULL && slow != fast) {
slow = slow->next;
fast = fast->next->next;
}
return slow == fast;
}
};
Java
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while(fast.next != null && fast.next.next != null && !(slow.equals(fast))) {
slow = slow.next;
fast = fast.next.next;
}
return slow.equals(fast);
}
}
四,解题过程
第一博
图一乐