Last active
December 30, 2015 09:39
-
-
Save maxcountryman/7810313 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Singly-Linked List | |
(definterface INode | |
(getCar []) | |
(getCdr []) | |
(setCar [x]) | |
(setCdr [x])) | |
(deftype Node | |
[^:volatile-mutable car ^:volatile-mutable cdr] | |
INode | |
(getCar [_] car) | |
(getCdr [_] cdr) | |
(setCar [this x] (set! car x) this) | |
(setCdr [this x] (set! cdr x) this) | |
clojure.lang.IPersistentCollection | |
(cons [this _] this)) | |
(definterface ILinkedList | |
(getHead [])) | |
(deftype LinkedList | |
[^:volatile-mutable head] | |
ILinkedList | |
(getHead [_] head) | |
clojure.lang.IPersistentCollection | |
(cons [this x] (set! head (Node. x head)) this) | |
clojure.lang.Seqable | |
(seq [this] | |
(loop [cur head acc ()] | |
(if-not cur | |
acc | |
(recur (.getCdr cur) | |
(concat acc (list [cur (.getCar cur) (.getCdr cur)])))))) | |
clojure.lang.ISeq | |
(first [_] head) | |
(next [this] (drop 1 (seq this))) | |
(more [this] (if-let [n (next this)] n ())) | |
clojure.lang.Reversible | |
(rseq [this] | |
(loop [new-head nil cur head nex (.getCdr cur)] | |
(if-not cur | |
(do (set! head new-head) this) | |
(do (.setCdr cur new-head) (recur cur nex (if nex (.getCdr nex)))))))) | |
(defn linked-list [& [cars]] | |
(let [ll (LinkedList. (Node. (first cars) nil))] | |
(reduce conj ll (rest cars)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment