Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions Data-Structures/Linked-List/RotateListRight.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,13 @@
* A LinkedList based solution for Rotating a List to the right by k places
*/

function main () {
function rotateListRight (head, k) {
/*
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 avoid global variables.

Link for the Problem: https://leetcode.com/problems/rotate-list/
*/
// 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) {
Expand All @@ -42,4 +34,4 @@ function main () {
return head
}

main()
export { rotateListRight }
33 changes: 33 additions & 0 deletions Data-Structures/Linked-List/test/RotateListRight.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { rotateListRight } from '../RotateListRight'
import { Node } from '../SinglyLinkedList'

describe('Rotate list by k steps', () => {
it('should shift every node by k steps towards right, shifts few tail nodes towards the start and change head of the list', () => {
// Case 0: when head is null
let headNode = rotateListRight(null, 0)
expect(headNode).toEqual(null)

// Creating list
headNode = new Node(10)
headNode.next = new Node(20)
headNode.next.next = new Node(30)
headNode.next.next.next = new Node(40)
headNode.next.next.next.next = new Node(50)

// Case 1: when k = 0 => List should be unaffected
headNode = rotateListRight(headNode, 0)
expect([headNode.data, headNode.next.data, headNode.next.next.data, headNode.next.next.next.data, headNode.next.next.next.next.data]).toEqual([10, 20, 30, 40, 50])

// Case 2: Rotate right by 2 steps
headNode = rotateListRight(headNode, 2)
expect([headNode.data, headNode.next.data, headNode.next.next.data, headNode.next.next.next.data, headNode.next.next.next.next.data]).toEqual([40, 50, 10, 20, 30])

// Case 3: Rotate right by 12 steps
headNode = rotateListRight(headNode, 12)
expect([headNode.data, headNode.next.data, headNode.next.next.data, headNode.next.next.next.data, headNode.next.next.next.next.data]).toEqual([20, 30, 40, 50, 10])

// Case 4: when k = length of the list = 5 => List should be unaffected
headNode = rotateListRight(headNode, 5)
expect([headNode.data, headNode.next.data, headNode.next.next.data, headNode.next.next.next.data, headNode.next.next.next.next.data]).toEqual([20, 30, 40, 50, 10])
})
})