Last active
January 6, 2019 00:53
-
-
Save j-quelly/b7e9049b68b5e4f4b4a86cf7f3a616cf to your computer and use it in GitHub Desktop.
Note: Try to solve this task in O(list size) time using O(1) additional space, since this is what you'll be asked during an interview. Given a singly linked list of integers l and a non-negative integer n, move the last n list nodes to the beginning of the linked list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Definition for singly-linked list: | |
// function ListNode(x) { | |
// this.value = x; | |
// this.next = null; | |
// } | |
// | |
function getArryFromList(l) { | |
let current = l; | |
const results = []; | |
while(current) { | |
results.push(current.value); | |
current = current.next; | |
} | |
return results; | |
} | |
function rearrangeLastN(l, n) { | |
const arr = getArryFromList(l); | |
if (n > arr.length || n === 0) { | |
return arr; | |
} | |
if (n >= 1) { | |
const front = arr.slice(arr.length - n); | |
arr.splice(arr.length - n); | |
return front.concat(arr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment