原list: ( ( 1 2 ) ( 3 4 ) )
转置: ( ( 3 4 ) ( 1 2 ) )
深度转置: ( ( 4 3 ) ( 2 1 ) )
( define tree ( list 1 ( list 2 ( list 3 4 ) 5 ) ( list 6 7 ) ) )
( define nil ‘() )
( define ( my-reverse items )
( define ( rev-imp items result )
( if ( null? items )
result
( rev-imp ( cdr items )
( cons ( car items ) result ) ) ) )
( rev-imp items nil ) )
( my-reverse items )
> ( my-reverse tree )
((6 7) (2 (3 4) 5) 1)
( define ( deep-reverse items )
( define ( deep-rev-if-required item )
( if ( not ( pair? item ) )
item
( deep-reverse item ) ) )
( define ( deep-rev-imp items result )
( if ( null? items )
result
( deep-rev-imp ( cdr items )
( cons ( deep-rev-if-required( car items ) )
result ) ) ) )
( deep-rev-imp items nil ) )
> ( deep-reverse tree )
((7 6) (5 (4 3) 2) 1)
或:
( define ( deep-reverse items )
( if ( pair? items )
( my-reverse ( map deep-reverse items ) )
items ) )
> ( deep-reverse tree )
((7 6) (5 (4 3) 2) 1)
Scheme 链表转置