Reverse list in Racket in O(n)

前端 未结 1 1699
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-27 14:53

I need to write a recursive function in Scheme which takes a list of atoms and reverses it in linear time. I am only allowed to use define, lambda, cons, car, cdr, cond, let, a

1条回答
  •  执笔经年
    2021-01-27 15:15

    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))
    

    0 讨论(0)
提交回复
热议问题