[ create a new paste ] login | about

Link: http://codepad.org/jsSIqs0M    [ raw code | output | fork ]

programmingpraxis - Scheme, pasted on Jun 24:
; swap list nodes

(define (swap-kth-nodes xs k)
  (let loop1 ((a xs) (b xs) (k (- k 1)))
    (if (null? a) xs
      (if (positive? k) (loop1 (cdr a) (cdr b) (- k 1))
        (let loop2 ((b b) (c xs))
          (if (pair? (cdr b)) (loop2 (cdr b) (cdr c))
            (if (eq? a c) xs
              (let ((t (car a)))
                (set-car! a (car c)) (set-car! c t)
                  xs))))))))

(display (swap-kth-nodes '() 3)) (newline)
(display (swap-kth-nodes '(1) 3)) (newline)
(display (swap-kth-nodes '(1 2) 3)) (newline)
(display (swap-kth-nodes '(1 2 3) 3)) (newline)
(display (swap-kth-nodes '(1 2 3 4) 3)) (newline)
(display (swap-kth-nodes '(1 2 3 4 5) 3)) (newline)
(display (swap-kth-nodes '(1 2 3 4 5 6) 3)) (newline)
(display (swap-kth-nodes '(1 2 3 4 5 6 7) 3)) (newline)
(display (swap-kth-nodes '(1 2 3 4 5 6 7 8) 3)) (newline)
(display (swap-kth-nodes '(1 2 3 4 5 6 7 8 9) 3)) (newline)


Output:
1
2
3
4
5
6
7
8
9
10
()
(1)
(1 2)
(3 2 1)
(1 3 2 4)
(1 2 3 4 5)
(1 2 4 3 5 6)
(1 2 5 4 3 6 7)
(1 2 6 4 5 3 7 8)
(1 2 7 4 5 6 3 8 9)


Create a new paste based on this one


Comments: