LeetCode: Rotate List Solution
Should draw for better imagination of how it worksApproach
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
1var rotateRight = function (head, k) {2 if (!head) return null34 let size = 05 for (let iter = head; iter; iter = iter.next) size++67 k %= size8 k = size - k - 1910 let tail = head11 let beforeTrimStart = head1213 while (tail.next) tail = tail.next14 while (k--) beforeTrimStart = beforeTrimStart.next1516 tail.next = head17 const trimStart = beforeTrimStart.next18 beforeTrimStart.next = null1920 return trimStart21}
Implementation (break and rebuild)
1var rotateRight = function (head, k) {2 if (!head) return null34 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 }2223 const arr = llistToArray(head)24 k %= arr.length25 k = arr.length - k2627 return arrayToLlist([...arr.slice(k), ...arr.slice(0, k)])28}
Comments
Loading comments...
Tags
leetcode
linked list
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Find Greatest Common Divisor of Array
Straight forward: min, max then gcd
Previous Post
LeetCode: Flatten a Multilevel Doubly Linked List
Naming variables is also important