Created
March 12, 2023 05:30
-
-
Save pjcodesjs/8a9be7c8aceb9120ca16aa0d9cf094c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(data, next = null) { | |
this.data = data; | |
this.next = next; | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this.head = null; | |
} | |
rotate(k) { | |
if (!this.head) { | |
return null; | |
} | |
let current = this.head; | |
let length = 1; | |
// Traverse the linked list to find its length and the last node | |
while (current.next) { | |
current = current.next; | |
length++; | |
} | |
// Set the next node of the last node to the current head node | |
current.next = this.head; | |
// Find the new head node by moving k nodes from the current head node | |
let newHeadIndex = length - k % length; | |
current = this.head; | |
let i = 0; | |
while (i < newHeadIndex - 1) { | |
current = current.next; | |
i++; | |
} | |
// Set the next node of the node at position k-1 to null | |
this.head = current.next; | |
current.next = null; | |
// Return the new head node | |
return this.head; | |
} | |
} | |
// Example usage | |
const list = new LinkedList(); | |
list.head = new Node(1); | |
list.head.next = new Node(2); | |
list.head.next.next = new Node(3); | |
list.head.next.next.next = new Node(4); | |
list.head.next.next.next.next = new Node(5); | |
list.rotate(2); // Output: Node { data: 4, next: Node { data: 5, next: Node { data: 1, next: Node { data: 2, next: Node { data: 3, next: null } } } } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment