2013-10-16 35 views

回答

3

如果你能发生变异的名单,这里有一个标准的方法:

(define (make-circular lst) 
    ; helper for finding the last pair in a list 
    (define (last-pair lst) 
    (if (null? (cdr lst)) 
     lst 
     (last-pair (cdr lst)))) 
     ; special case: if the list is empty 
    (cond ((null? lst) '()) 
     (else 
     ; set the last pair to point to the head of the list 
     (set-cdr! (last-pair lst) lst) 
     lst))) 

注意的是,以上将修改输入列表中。除此之外,它按预期工作:

(make-circular '(1 2 3 4 5)) 
=> #0=(1 2 3 4 5 . #0#) 

(car (cdr (cdr (cdr (cdr (cdr (make-circular '(1 2 3 4 5)))))))) 
=> 1 
+0

祝福你,奥斯卡。 –

+1

@xuinkrbin。谢谢,永远是我的荣幸:) –

2

当您使用SRFIs这是很简单的:

(使用SRFI-1) (定义L“(1 2 3 4)) (申请圆形列表l)