# LeetCode: Rotate List Solution

Should draw for better imagination of how it works

## Approach

Find the node for the trim to start, call this the trim list

Attach the tail of the trim list to original head

Detach the node before trim list, point its

next
to
null
, to avoid cyclic

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var rotateRight = function (head, k) {2  if (!head) return null3
4  let size = 05  for (let iter = head; iter; iter = iter.next) size++6
7  k %= size8  k = size - k - 19
13  while (tail.next) tail = tail.next14  while (k--) beforeTrimStart = beforeTrimStart.next15
16  tail.next = head17  const trimStart = beforeTrimStart.next18  beforeTrimStart.next = null19
20  return trimStart21}```

## Implementation (break and rebuild)

```1var rotateRight = function (head, k) {2  if (!head) return null3
4  const llistToArray = llist => {5    let iter = llist6    const res = []7    while (iter) {8      res.push(iter.val)9      iter = iter.next10    }11    return res12  }13  const arrayToLlist = arr => {14    let dummy = (iter = new ListNode())15    arr.forEach(el => {16      const node = new ListNode(el)17      iter.next = node18      iter = iter.next19    })20    return dummy.next21  }22
23  const arr = llistToArray(head)24  k %= arr.length25  k = arr.length - k26
27  return arrayToLlist([...arr.slice(k), ...arr.slice(0, k)])28}```

leetcode

## Next Post

LeetCode: Find Greatest Common Divisor of Array

Aug 22, 2021

Straight forward: min, max then gcd

## Previous Post

LeetCode: Flatten a Multilevel Doubly Linked List

Aug 21, 2021

Naming variables is also important

Search Posts