Reverse the Second Half
For a list of n nodes, reverse the order of the last n // 2 nodes and leave the first nodes as they are (for an odd n the middle node stays in the first part). Return the head. The list is passed in as head.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
head [1,2,3,4,5,6]
returns [1,2,3,6,5,4]
The last three nodes 4,5,6 become 6,5,4.
Example 2
head [1,2,3,4,5]
returns [1,2,3,5,4]
The last two nodes 4,5 become 5,4.
Constraints
0 <= number of nodes <= 100-100 <= Node.val <= 100
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Rotate ListMedium
- Sort ListMedium
- Split Linked List in PartsMedium
- Swap Kth From Start and EndMedium
- Where the Cycle StartsMedium
- Complete the MirrorHard
- Deal and WeaveHard
- Fold Many TimesHard