Reorder List
You are given the head of a singly linked list L0 → L1 → … → Ln-1 → Ln. Rearrange its nodes in place into the order
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
taking nodes alternately from the front and from the back.
Only change next pointers: don't modify node values or create new nodes. The function returns nothing; the tests read the list starting from the original head after your function runs.
Constraints
- The list has between
0and5 * 10^4nodes. 1 <= Node.val <= 1000
Examples
Example 1
Input: head = [1,2,3,4,5,6] Output: [1,6,2,5,3,4]
Take from the front and the back in turn: 1, 6, 2, 5, 3, 4. The test reads the list starting from your original head.
Example 2
Input: head = [10,20,30,40,50] Output: [10,50,20,40,30]
With an odd length, the middle node (30) ends up last.
Example 3
Input: head = [1] Output: [1]
One node: nothing to move.
JavaScript you'll use: Linked list and tree nodes
/**
* Linked list nodes are provided (you don't need to define them):
* class ListNode { constructor(val = 0, next = null) { this.val = val; this.next = next; } }
*/
/**
* @param {ListNode} head
* @return {void}
*/
function reorderList(head) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.