Share my easy Java solution


  • 0
    M
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null || head.next == null || k <= 0) { return head; }
            int count = 0;
            ListNode tail = null;
            for (ListNode p = head; p != null; p = p.next) {
                ++count;
                if (p.next == null) {
                    tail = p;
                }
            }
            int kk = k % count;
            if (kk == 0) { return head; }
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode breakNode = dummy;
            for (int i = 0; i < count - kk; ++i) { breakNode = breakNode.next; }
            dummy.next = breakNode.next;
            tail.next = head;
            breakNode.next = null;
            return dummy.next;
        }
    }

Log in to reply
 

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