题目描述:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1输出:true解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:
输入:head = [1,2], pos = 0输出:true解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:
输入:head = [1], pos = -1输出:false解释:链表中没有环。
算法实现:
哈希法
/*** Definition for singly-linked list.* function ListNode(val) {* this.val = val;* this.next = null;* }*//*** @param {ListNode} head* @return {boolean}*/var hasCycle = function(head) {if (head === null || head.next === null) return falsewhile (head) {if (head.val === 'flag') {return true} else {head.val = 'flag'}head = head.next}return false};
双指针法
/*** Definition for singly-linked list.* function ListNode(val) {* this.val = val;* this.next = null;* }*//*** @param {ListNode} head* @return {boolean}*/var hasCycle = function(head) {if (head === null || head.next === null) return falsevar slow = headvar fast = head.nextwhile (slow != fast){if (fast === null || fast.next === null) return falseslow = slow.nextfast = fast.next.next}return true};
思考;
哈希法很容易想到,通过遍历给标记,再判断即可,双指针法很精妙,学到了。
总结:
进一步学习了哈希法,也理解了一些双指针法的运用。

