14. A circular linked list,

Subject description:

Given a list, the list is determined whether a ring.
To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.
Example 1:

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

Code:

JavaScript

  • Hash, ES6 the map application, the value added to the list in the map key, the method has application during traversal is determined whether it contains the same key.
  • Time complexity: O (n)
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
    var map = new Map()
    while (head) {
        if (map.has(head)) {
            return true
        } else {
            map.set(head)
        }
        head = head.next
    }
    return false
};

Here Insert Picture Description

  • Double pointer, fast and slow, if it is circular linked list, will eventually meet.
  • Time complexity: O (n)
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
    var fast = head
    var slow = head
    while (fast && fast.next) {
        fast = fast.next.next
        slow = slow.next
        if (fast == slow) {
            return true
        }
    }
    return false
};

Here Insert Picture Description

Published 14 original articles · won praise 1 · views 1671

Guess you like

Origin blog.csdn.net/weixin_45569004/article/details/104760676