diff --git a/solution/0141.Linked List Cycle/Solution2.js b/solution/0141.Linked List Cycle/Solution2.js new file mode 100644 index 0000000000000..842d5817b59d6 --- /dev/null +++ b/solution/0141.Linked List Cycle/Solution2.js @@ -0,0 +1,24 @@ +var hasCycle2 = function(head) { + let slow = head + let fast = head + while (fast !== null && fast.next !== null) { + slow = slow.next + fast = fast.next.next + if (slow === fast) { + return true + } + } + return false +} + +var hasCycle3 = function(head) { + let arr = [] + while (head !== null) { + if (arr.includes(head)) { + return true + } + arr.push(head) + head = head.next + } + return false +} \ No newline at end of file diff --git a/solution/0160.Intersection of Two Linked Lists/Solution.js b/solution/0160.Intersection of Two Linked Lists/Solution.js new file mode 100644 index 0000000000000..85fa7ca7bdbc1 --- /dev/null +++ b/solution/0160.Intersection of Two Linked Lists/Solution.js @@ -0,0 +1,45 @@ +var getIntersectionNode2 = function(headA, headB) { + if (!headA || !headB) { + return null + } + let q = headA, p = headB + let lengthA = 1 + let lengthB = 1 + while(q.next) { + q = q.next + lengthA++ + } + while (p.next) { + p = p.next + lengthB++ + } + if (q !== p) { + return null + } + + q = headA, p = headB + if (lengthA > lengthB) { + for (let i = 0; i < lengthA - lengthB; i++) { + q = q.next + } + } else { + for (let i = 0; i < lengthB - lengthA; i++) { + p = p.next + } + } + while (q !== p && q !== null) { + q = q.next + p = p.next + } + return q +}; + +var getIntersectionNode = function(headA, headB) { + let p1 = headA; + let p2 = headB; + while (p1 != p2) { + p1 = p1 ? p1.next : headB; + p2 = p2 ? p2.next : headA; + } + return p1; +} \ No newline at end of file