Reverse list in Racket in O(n)

本小妞迷上赌 提交于 2019-12-02 09:04:19

The problem is that if (reverse (cdr lat)) returns a list eg (3 2) then (cons '(3 2) (1)) turns into ((3 2) 1).

A classical way to do this would be to make a local procedure that takes an accumulator as well as the argument of the global procedure. As you are iterating the list from the beginning to the end you accumulate a list from the end to the beginning making it the exact reverse order from the argument. When the iterated list is null your answer is in the accumulator. As you notice you iterate once each element and when you hit the empty list you return the accumulator it's a perfect O(n)

As a hint:

(define (myreverse lst)
  (define (myreverse-aux lst acc)
    (if (null? <??>)
        <??>
        (myreverse-aux <??> (cons <??> <??>))))
  (myreverse-aux <??> <??>))

Here is a version using foldl

(define (myreverse lst)
  (foldl cons '() lst))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!