Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
45 changes: 0 additions & 45 deletions Data-Structures/Linked-List/RotateListRight.js

This file was deleted.

36 changes: 34 additions & 2 deletions Data-Structures/Linked-List/SinglyLinkedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* a singly linked list.
*/

// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt, findMiddle, get, clean
// Methods - size, head, addLast, addFirst, addAt, removeFirst, removeLast, remove, removeAt, indexOf, isEmpty, elementAt, findMiddle, get, clean, rotateListRight

class Node {
constructor (data) {
Expand All @@ -16,9 +16,15 @@ class Node {
}

class LinkedList {
constructor () {
constructor (listOfValues) {
this.headNode = null
this.length = 0

if (listOfValues instanceof Array) {
for (let i = 0; i < listOfValues.length; i++) {
this.addLast(listOfValues[i])
}
}
}

// initiates the currentNode and currentIndex and return as an object
Expand Down Expand Up @@ -224,6 +230,32 @@ class LinkedList {
return list
}

// Method for Rotating a List to the right by k places
rotateListRight (k) {
let i = 0
let current = this.headNode
while (current) {
i++
current = current.next
}
k %= i
current = this.headNode
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 = this.headNode
this.headNode = current
}
}
}

// Method to iterate over the LinkedList
iterator () {
let { currentNode } = this.initiateNodeAndIndex()
Expand Down
25 changes: 25 additions & 0 deletions Data-Structures/Linked-List/test/SinglyLinkedList.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,29 @@ describe('SinglyLinkedList', () => {
list.clean()
expect(list.isEmpty()).toBe(true)
})

it('should shift every node by k steps towards right, shifts tail nodes towards the start and change head of the list', () => {
// Case 0: When head of list is null
const tempNode = new LinkedList()
expect(tempNode.get()).toEqual([])

// Creating list
const headNode = new LinkedList([10, 20, 30, 40, 50])

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

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

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

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