From e58da22dbea922c4425d6eeabd9eed9274ed41c5 Mon Sep 17 00:00:00 2001 From: KamillaKhabibrakhmanova Date: Sat, 16 Jul 2016 18:14:27 -0400 Subject: [PATCH] solution to 2.6 --- Chapter2-LinkedLists/2.6-FindLoop.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Chapter2-LinkedLists/2.6-FindLoop.js diff --git a/Chapter2-LinkedLists/2.6-FindLoop.js b/Chapter2-LinkedLists/2.6-FindLoop.js new file mode 100644 index 0000000..800e6cb --- /dev/null +++ b/Chapter2-LinkedLists/2.6-FindLoop.js @@ -0,0 +1,22 @@ +/* +Problem: Given a circular linked list, implement an algorithm which returns the node at the beginning of the loop. +*/ + +//built on top of linked list in data structures +LinkedList.prototype.findLoop = function() { + var n = this.head; + var storedValues = []; + var res = null; + while (n) { + if (storedValues.indexOf(n.data) < 0) { + storedValues.push(n.data); + n = n.next; + } else { + res = n.data; + break; + } + } + return res; +}; + +//runtime: n^2 \ No newline at end of file