Python 实现 # Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = NoneclassSolution(object):defhasCycle(self, head):""" :type head: ListNode :rtype: bool """ifheadisNoneorhead.nextisNone:returnFalseslow, fast = head, ...
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: # 空链表或链表只有一个节点,无环 if not head or head.next == None: return False # 初始化快慢指针 fast = slow = head ...
solution 2 两指针 //整两快慢指针,快的先遇到空,则false;快的等于慢的,则truepublicclassSolution{publicbooleanhasCycle(ListNode head){if(head ==null|| head.next ==null) {returnfalse; }ListNodeslow=head;ListNodefast=head.next;while(slow != fast) {if(fast ==null|| fast.next ==null) {retur...
* struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { /*解法1:快慢指针*/ // if (head == NULL || head->next == NULL) { // return false; // } // ListNode *slow...
Notes: 2. Examples: 3.Solutions: 1/**2* Created by sheepcore on 2019-05-143* Definition for singly-linked list.4* class ListNode {5* int val;6* ListNode next;7* ListNode(int x) {8* val = x;9* next = null;10* }11* }12*/13publicbooleanhasCycle(ListNode head) {14ListNode p...
class Solution { public: bool hasCycle(ListNode *head) { unordered_map<ListNode *, char> nodemap; // 散列表功能 ListNode *temp = head; while (temp) { if (nodemap.count(temp) == 1) return true; // 当前节点已存在于 map 中,则说明有环 nodemap[temp] = '0'; temp = temp->next;...
* }*/publicclassSolution {publicbooleanhasCycle(ListNode head) { HashSet<ListNode> s =newHashSet<>();if(head ==null) {returnfalse; }while(head !=null) {if(s.contains(head) ==false) { s.add(head); head=head.next; }else{returntrue; ...
*/ public class Solution { public boolean hasCycle(ListNode head) { if(head == null||head.next == null)return false; ListNode p1 = head,p2 = p1; while(true) { p1 = p1.next; for(int i = 0;i < 2;i++) if(p2.next != null) ...
LeetCode--141--环形链表 问题描述: 给定一个链表,判断链表中是否有环。 思路:用快的指针追慢的指针,只要有圈,一定能追上。 错误: 1classSolution(object):2defhasCycle(self, head):3"""4:type head: ListNode5:rtype: bool6"""7ifhead == Noneorhead.next ==None:8returnFalse9p =head.next10q ...
classSolution: def hasCycle(self, head: ListNode)->bool:ifhead==None:returnFalseifhead.next==None:returnFalse s={}whilehead:ifs.get(head):returnTrue s[head]=1head=head.nextreturnFalse 方法二Python: classSolution: def hasCycle(self, head: ListNode)->bool:ifhead==None:returnFalseifhead.next...