알고리즘/LeetCode

61. Rotate List

JUHANPAPA 2022. 5. 19. 08:47

 

Given the head of a linked list, rotate the list to the right by k places.

 

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Input: head = [0,1,2], k = 4
Output: [2,0,1]

 

Constraints:

  • The number of nodes in the list is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 109

 

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null ) return head;
        
        ListNode end = head;
        
        
        int len = 1;
        while(end.next !=null) {
            end = end.next;
            len++;
        }
        System.out.println("end.val: " + end.val + ", len:" + len);
        
        int move = len - (k % len);
        ListNode newHead = head;
        ListNode newEnd = head;
        for(int i=0; i< move -1; i++) {
            newEnd = newEnd.next;
        }
        for(int i=0; i< move ; i++) {
            newHead = newHead.next;
        }
        if(newHead != null) {
            newEnd.next = null;
            end.next = head;
        }
        
        return newHead == null ? head : newHead;
    }
}