Home [Medium] Rotate List
Post
Cancel

[Medium] Rotate List

‘Rotate List (Medium)’


📌 Problem

https://leetcode.com/problems/rotate-list/

📌 Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * 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 || head.next == null) return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode fast = dummy, slow = dummy;
        
        int len;
        // Get the total length of the list
        for (len = 0; fast.next != null; len++) {
            fast = fast.next;
        }
        // Get the (len - k%len)th node
        for (int j = len - (k % len); j > 0; j--) {
            slow = slow.next;
        }
        
        // Do the rotation
        fast.next = dummy.next;
        dummy.next = slow.next;
        slow.next = null;
        
        return dummy.next;
    }
}
This post is licensed under CC BY 4.0 by the author.

[Medium] Swap Nodes in Pairs

[Medium] Delete Node in a Linked List

Comments powered by Disqus.