- 1、题目描述:
- 2、题目链接:
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9?tpId=117&&tqId=34925&rp=1&ru=/activity/oj&qru=/ta/job-code-high/question-ranking
-3、 设计思想:
详细操作流程看下图:
-4、视频讲解链接B站视频讲解
-5、代码:
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* fast = head->next;//快指针
ListNode *slow = head;//慢指针
while(slow != fast){//快慢指针不相遇就要遍历
if(fast == NULL || fast->next == NULL) return false;
fast = fast->next->next;//快指针移动两格
slow = slow->next;//慢指针移动一格
}
return true;
}
};
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 fast = head.next;//快指针
ListNode slow = head;//慢指针
while(fast != slow){//快慢指针不相遇就要遍历
if(fast == null || fast.next == null){
return false;
}
fast = fast.next.next;//快指针移动两格
slow = slow.next;//慢指针移动一格
}
return true;
}
}Python版本:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @return bool布尔型
#
class Solution:
def hasCycle(self , head ):
# write code here
if head == None or head.next == None:
return False
fast = head.next#快指针
slow = head#慢指针
while fast != slow:#快慢指针不相遇就要遍历
if fast == None or fast.next == None:
return False
fast = fast.next.next#快指针移动两格
slow = slow.next#慢指针移动一格
return True

京公网安备 11010502036488号