Utopi
a

环形链表

Discussion is really funny!

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer

pos
which represents the position (0-indexed) in the linked list where tail connects to. If
pos
is
-1
, then there is no cycle in the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node.

img

Example 2:

Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where tail connects to the first node.

img

Example 3:

Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list.

img

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

简单解释一下

这题目综述写得糟糕的很,很多人(包括我)看不懂到底是要干什么。其实就是给你一个链表,让你判断是不是环形链表,环形链表永远跑不到尾巴。

Mine

/** * 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) { ListNode slow = head; if(head == null ) return false; ListNode fast = head.next; if (fast == null) { return false; } try{ do { slow = slow.next; fast = fast.next.next; if (fast == slow) { return true; } } while (fast != null); }catch(Exception e){ return false; } return false; } }

双指针法注意.next.next找不到的情况。

Discussion

今天才看到有讨论区,真是人才辈出!

Delay

bool hasCycle(struct ListNode *head) { if(head){ int times = 0; struct ListNode *root = head; while(root->next){ root = root->next; times++; if(times>10000){ return true; } } } return false;

" 我帮你们测试好了,样例最多的有8029个数据 "

public class Solution { public boolean hasCycle(ListNode head) { int count=8029; while(head!=null&&count>0){ head=head.next; count--; } if(head==null) return false; return true; } }

”想要取巧,bjfuvth什么的怪字符串不可取“

var hasCycle = function(head) { let s = Symbol('fuck') while(head){ if(head[s]) return true else head[s] = true head = head.next } return false };

???

var hasCycle = function(head) { try{ JSON.stringify(head); } catch(e){ return true; } return false; };

链表部分就全部做完了!