From da21e7d326895be84e55bae589a105dc7cfc4661 Mon Sep 17 00:00:00 2001 From: Omkarnath Parida Date: Tue, 6 Oct 2020 15:09:33 +0530 Subject: [PATCH 1/2] Added Rotate List Right by k places to the list --- .../Linked-List/RotateListRight.js | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Data-Structures/Linked-List/RotateListRight.js diff --git a/Data-Structures/Linked-List/RotateListRight.js b/Data-Structures/Linked-List/RotateListRight.js new file mode 100644 index 000000000..473990765 --- /dev/null +++ b/Data-Structures/Linked-List/RotateListRight.js @@ -0,0 +1,43 @@ +/** + * A LinkedList based solution for Rotating a List to the right by k places + */ + +function main () { + /* + Problem Statement: + Given a linked list, rotate the list to the right by k places, where k is non-negative. + + Note: + * While Solving the problem in given link below, don't use main() function. + * Just use only the code inside main() function. + * The purpose of using main() function here is to aviod global variables. + + Link for the Problem: https://leetcode.com/problems/rotate-list/ + */ + const head = '', k = '' // Reference to both head and k is given in the problem. So please ignore this line + let i = 0; + let current = head + while (current) { + i++ + current = current.next + } + k %= i + current = head + let prev = null + while (k--) { + if (!current || !current.next) { + return current + } else { + while (current.next) { + prev = current + current = current.next + } + prev.next = current.next + current.next = head + head = current + } + } + return head +} + +main() From 35cade3908593a79cbdd47f10e125509be56de17 Mon Sep 17 00:00:00 2001 From: Omkarnath Parida Date: Tue, 6 Oct 2020 15:14:39 +0530 Subject: [PATCH 2/2] Changed Styles as per guidelines --- Data-Structures/Linked-List/RotateListRight.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Data-Structures/Linked-List/RotateListRight.js b/Data-Structures/Linked-List/RotateListRight.js index 473990765..8acc7c767 100644 --- a/Data-Structures/Linked-List/RotateListRight.js +++ b/Data-Structures/Linked-List/RotateListRight.js @@ -14,8 +14,10 @@ function main () { Link for the Problem: https://leetcode.com/problems/rotate-list/ */ - const head = '', k = '' // Reference to both head and k is given in the problem. So please ignore this line - let i = 0; + // Reference to both head and k is given in the problem. So please ignore below two lines + let head = '' + let k = '' + let i = 0 let current = head while (current) { i++