﻿ 计划 – 了解深度逆转 - 代码日志

#### 计划 – 了解深度逆转

(附加
(深度反转(cdr lst))
(列表(深反(汽车))))))

``````(define (deep-reverse lst)
(cond ((null? lst) '() )
((pair? (car lst))
(append
(deep-reverse (cdr lst))
(list (deep-reverse (car lst)))))
(else
(append
(deep-reverse (cdr lst))
(list (car lst))))))
``````

``````(list
'e
'(b c d)
'a
)
``````

``````(list
'e
(deep-reverse '(b c d))
'a
)
``````

``````(list
'e
'(d c b)
'a
)
``````

``````(define (deep-reverse ls)
(define (deep-reverse-2 ls acc)
(if (null? ls)
acc
(if (list? (car ls))
(deep-reverse-2 (cdr ls) (cons (deep-reverse (car ls)) acc));  If adding  a list, reverse it first
(deep-reverse-2 (cdr ls) (cons (car ls) acc)))))
(deep-reverse-2 ls '()))
``````

``````(deep-reverse '(a (b c d) e)) -> '(e (d c b) a)
``````

``````(deep-reverse-2 '(a (b c d) e) '()); Which calls
(deep-reverse-2 '((b c d) e)  '(a)); which is the same as
(deep-reverse-2 '(e) (cons (deep-reverse-2 '(b c d) '()) '(a))); it calls deep-reverse on the list '(b c d) before consing it on.
(deep-reverse-2 '(e) (cons (deep-reverse-2 '(c d)  '(b)) '(a)))
(deep-reverse-2 '(e) (cons (deep-reverse-2 '(d)  '(c b)) '(a)))
(deep-reverse-2 '(e) (cons '(d c b) '(a)))
(deep-reverse-2 '(e)  '((d c b) a))
(deep-reverse-2 '() '(e (d c b) a))
'(e (d c b) a)
``````