Sharing my Java solution


  • -1
    public class Solution {
        public ListNode rotateRight(ListNode head, int n) {
            
            if (head == null || n == 0) {
                return head;
            }
            
            List<ListNode> nodes = new ArrayList<ListNode>();
            ListNode curr = head;
            while (curr != null) {
                nodes.add(curr);
                curr = curr.next;
            }
            
            n = n % nodes.size();
            if (n == 0) {
                return head;
            }
            
            nodes.get(nodes.size() - 1).next = nodes.get(0);
            nodes.get(nodes.size() - 1 - n).next = null;
            
            return nodes.get(nodes.size() - n);
        }
    }

  • 0
    S

    Bad solution using extra O(n) space.


Log in to reply
 

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