Given the head of a linked list, rotate the list to the right by k places.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Example 2:
Input: head = [0,1,2], k = 4
Output: [2,0,1]
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null||head.next==null) return head;
ListNode index = head;
int len = 1; //計算長度
while(index.next != null){
index = index.next;
len++;
}
index.next = head;
for(int i =1; i< len - k % len;i++){
head = head.next;
}
ListNode res = head.next;
head.next = null;
return res;
}
}
Time Complexity: O(n) Space Complexity: O(1)
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
// Create a linked list from the array
ListNode head = createLinkedList(new int[]{1, 2, 3, 4, 5,6});
// Rotate the linked list
int n = 2;
ListNode rotatedHead = solution.rotateRight(head, n);
// Print the resulting linked list
printLinkedList(rotatedHead);
}
// Helper method to create a linked list from an array
private static ListNode createLinkedList(int[] nums) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
for (int num : nums) {
current.next = new ListNode(num);
current = current.next;
}
return dummy.next;
}
// Helper method to print the elements of a linked list
private static void printLinkedList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
System.out.println();
}
}