Share my AC JAVA solution


  • 0
    W
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null || head.next == null) return head;
            ListNode runner = head;
            int len = 0;
            while (runner != null) {
                runner = runner.next;
                len++;
            }
            k = k % len;
            if (k == 0) return head;
            
            ListNode node1 = head;
            ListNode node2 = head;
            for (int i = 0; i < k; i++) {
                node2 = node2.next;
            }
            while (node2.next != null) {
                node2 = node2.next;
                node1 = node1.next;
            }
            node2.next = head;
            ListNode newHead = node1.next;
            node1.next = null;
            return newHead;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.