leetcode-面试题 02.08. 环路检测

108 阅读1分钟

image.png leetcode原题

解题思路

  • 遍历链表,如果当前节点有 tag 标记,说明之前遍历过该节点,此时再次遍历到该节点,说明该节点就是链表环路的开头节点,将其返回即可
  • 否则给该节点 tag 属性赋值(赋值内容没有要求,只要能判断到是否有标记即可),然后继续向后遍历链表
  • 如果直到链表末尾,都没有遇到一个之前遍历过的节点,说明链表没有环,返回 null
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function(head) {
  // 遍历链表
  while(head){
    // 如果当前节点有tag,说明之前遍历过,返回该节点
    if(head.tag) return head;
    // 反之给节点打上tag
    head.tag = 'been';
    head = head.next;
  }
  // 如果遍历完链表没有遇到之前遍历过的节点,说明链表没有环,返回null
  return null;
};