Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Create linked-list-cycle-ii.js #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 17, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions LeetcodeProblems/linked-list-cycle-ii.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
https://leetcode.com/problems/linked-list-cycle-ii/description/

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?
*/


// Optimal solution
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function(head) {
if (head === null)
return null;

var slow = head;
var fast = head;

while(fast.next !== null && fast.next.next !== null) {
slow = slow.next;
fast = fast.next.next;
if(fast == slow) {
var a = head;
var b = slow;
while(a !== b) {
a = a.next;
b = b.next;
}
return a;
}
}
return null;
};

// Naiver solution using a Set
var detectCycle2 = function(head) {
if(head === null || head.next === null) {
return null;
}
var setNodes = new Set();
var iter = head;
while(iter !== null) {
if(setNodes.has(iter)) {
return iter;
}
setNodes.add(iter);
iter = iter.next
}
return null;
};

var main = function() {
const head = buildCycle();
console.log(detectCycle(head));
}
main();

function ListNode(val) {
this.val = val;
this.next = null;
}

function buildCycle() {
var node1 = new ListNode(1);
var node2 = new ListNode(2);
var node3 = new ListNode(3);
var node4 = new ListNode(4);
var node5 = new ListNode(5);

node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node2;

/* 1 -> 2 -> 3 -> 4 -> 5
\ /
- - - - -
*/
return node1;
}

main();
module.exports.main = main;