Skip to content

Commit 496f05c

Browse files
Merge pull request Pradeepsingh61#604 from harshitpandey-26/patch-5
Create rotateList.js
2 parents 3818661 + 81b433f commit 496f05c

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Author: HarshitKumarPandey
2+
// Date: 2025-10-09
3+
// Description: Rotate a singly linked list to the right by k positions.
4+
5+
class ListNode {
6+
constructor(val = 0, next = null) {
7+
this.val = val;
8+
this.next = next;
9+
}
10+
}
11+
12+
function rotateRight(head, k) {
13+
if (!head || !head.next || k === 0) return head;
14+
15+
// Step 1: Find the length of the list
16+
let length = 1;
17+
let tail = head;
18+
while (tail.next) {
19+
tail = tail.next;
20+
length++;
21+
}
22+
23+
// Step 2: Make it circular
24+
tail.next = head;
25+
26+
// Step 3: Find new tail: (length - k % length - 1)th node
27+
k = k % length;
28+
let stepsToNewHead = length - k;
29+
let newTail = tail;
30+
while (stepsToNewHead-- > 0) {
31+
newTail = newTail.next;
32+
}
33+
34+
const newHead = newTail.next;
35+
newTail.next = null; // break the circle
36+
37+
return newHead;
38+
}
39+
40+
// Helper function to print linked list
41+
function printList(head) {
42+
const values = [];
43+
let curr = head;
44+
while (curr) {
45+
values.push(curr.val);
46+
curr = curr.next;
47+
}
48+
console.log(values.join(" -> "));
49+
}
50+
51+
// Example usage
52+
const head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
53+
const k = 2;
54+
55+
console.log("Original List:");
56+
printList(head);
57+
58+
const rotated = rotateRight(head, k);
59+
console.log("Rotated List:");
60+
printList(rotated); // Output: 4 -> 5 -> 1 -> 2 -> 3

0 commit comments

Comments
 (0)