I need to create a program that will reverse a list destructively. For example lets say..
scm> (define L (list 1 2 3 4))
scm> (reverse! L)
(4 3 2 1)
scm> L
(1)
Where L becomes the last element of the reversed list. I know I am supposed to use set-cdr! somehow but cannot figure out how to implement it.
Because this looks like homework, I can’t give you a straight answer. I’ll show you the general structure of the solution, so you can figure out the details and fill-in the blanks:
In the above code:
letfor simplicity, given that another parameter is neededaccparameter is defined, to serve as the accumulator for the reversed listNow, for the recursive step:
<?1?>we need to obtain a reference to the rest of the list and save it, given that we’re going to modify it(set-cdr! <?2?> <?3?>). You’ll have to set the next element of the current list to the previously accumulated, reversed listNotice that in the end, the
lstreference got modified in-place and now is pointing to the last element of the list. If you needlstto point to the reversed list, then simply do this:The procedure described reverses a list destructively and doesn’t create a new list (no
consoperations are used.)