2013-10-16 31 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)