Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (defun rotate-list (list)
- (cond
- ((endp list)) ; 0 elements
- ((endp (rest list))) ; 1 element
- ((endp (rest (rest list))) ; 2 elements
- (rotatef (car list) (cadr list)))
- ((endp (rest (rest (rest list)))) ; 3 elements
- (rotatef (car list) (cadr list) (caddr list)))
- (t
- ;; Principle:
- ;; 1- the first and last cons are not moved, their car are updated.
- ;; 2- the second cons is moved to the before last cons position.
- ;; 3- the other conses are not changed.
- ;; (a . (b . (c . (d … . (e . (f . nil))))))
- ;; (a . (c . (d … . (e . (b . (f . nil))))))
- (rotatef (car (last list))
- (car list)
- (car (cdr list)))
- (rotatef (cdr (last list 2))
- (cdr list)
- (cdr (cdr list)))))
- list)
- (dolist (test '(()
- (1)
- (1 2)
- (1 2 3)
- (1 2 3 4)
- (1 2 3 4 5)
- (1 2 3 4 5 6)))
- (let ((test (copy-list test)))
- (print (rotate-list test))))
- nil
- (1)
- (2 1)
- (2 3 1)
- (2 3 4 1)
- (2 3 4 5 1)
- (2 3 4 5 6 1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement