Problem 1
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes’ values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
Idea
- split from middle (fast-slow-pointer in java usually); ({1 2 3 4} => {1 2} {3 4})
- reverse the after one ({3 4} => {4 3});
- weave.
Notice that if list length is odd, clojure map doesn’t work well:
Here we use
- split-at
- reverse
- concat
- mapcat
- count
- drop
Solution
Improvements
Seeking for better solution now :(
I think the concat part is urgly.
Updated
We can write a map-all
to extend map
like what partition-all
to partiion
:
Thanks @dennis, @xhh a lot!