- 1、题目描述:
-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) {
set<ListNode *> se;//定义一个集合
while(head != NULL){//如果头节点不为空,就遍历链表
if(se.count(head)){//判断当前节点是否出现过,如果出现过就返回true
return true;
}
se.insert(head);//如果没有出现过就插入
head = head->next;//head等于下一个节点
} return false;
}
};
Java版本:
import java.util.*;
/**
* 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) {
Set<ListNode> se = new HashSet<ListNode>();//定义一个集合
while (head != null) {//如果头节点不为空,就遍历链表
if (se.contains(head)) {//判断当前节点是否出现过,如果出现过就返回true
return true;
}
se.add(head);//如果没有出现过就插入
head = head.next;//head等于下一个节点
}
return false;
}
}
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
se = set()#定义一个集合
while head != None:#如果头节点不为空,就遍历链表
if head in se:#判断当前节点是否出现过,如果出现过就返回true
return True
se.add(head)#如果没有出现过就插入
head = head.next#head等于下一个节点
return False

京公网安备 11010502036488号