Rotate a linked list to the right by k places The task


  Given a linked list and a positive integer k, rotate the list to the
  right by k places.
  
  For example, given the linked list 7 -> 7 -> 3 -> 5 and k = 2, it
  should become 3 -> 5 -> 7 -> 7.
  
  Given the linked list 1 -> 2 -> 3 -> 4 -> 5 and k = 3, it should
  become 3 -> 4 -> 5 -> 1 -> 2.


My solution

class LinkedNode {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }
}

const n4 = new LinkedNode(5);
const n3 = new LinkedNode(3, n4);
const n2 = new LinkedNode(7, n3);
const n1 = new LinkedNode(7, n2);

let n = n1;

const rotate = (l, k) =&gt; {
  let p = l;
  const first = l;
  let last;
  let res;
  let i = 0;
  while(p) {
    i++;
    if (!p.next) { last = p; }
    p = p.next;
  }
  const size = i;
  if (!(k % size)) { return l; }
  const aim = size - (k % size) - 1;
  p = l;
  i = 0;
  while (p) {
    if (i++ === aim) {
      res = p.next;
      p.next = null;
      last.next = first;
      return res;
    }
    p = p.next;
  }
};

n = rotate(n, 0);
while (n) {
  console.log(n.value);
  n = n.next;
}
You started to write a class, but then stopped. You should continue. There are three things that are potentially \$O(n)\$ in this problem: 


You need to know the length of the list.
You need to know the last node of the list.
You need to know the k-1th node of the list.


Two of those obviously go together, so you could justify writing a helper method that returns them both. The third one is arbitrary enough that there's not really any way to speed it up.

If you are in some kind of timed environment, you'll definitely want to wrap the list in a class and cache the last pointer and the size of the list.
If you do that, you can quickly compute k % size and then find #3, which will be \$O(n)\$. 

If I were trying to write challenges for a timed competition, I would include a large list and k = 2 * n - 1.

I see several obvious methods in your code, including a more sophisticated constructor that could take an array (perhaps an outer LinkedList class), the length operation, the get_last operation, the get_item operation, the print or perhaps map operation, and obviously missing is the compare operation.

You should probably check for k == 0 before finding the last item. I can easily see a time-limit-exceeded trap being to construct a huge list, then do a rotate with k=0.