Hackerrank Insert a node at a specific position in a linked list
Challenge
I loop starting from the head, until I reach the position where I want to insert the new node. I create the new node and make the next node of the new node, what the next node of the current node was, and I set the next node of the current node as the new node.
(definterface ISinglyLinkedListNode
(getdata [])
(getnext [])
(setdata [node-data])
(setnext [next-ptr]))
(deftype SinglyLinkedListNode [^:volatile-mutable data ^:volatile-mutable next]
ISinglyLinkedListNode
(getdata [_] data)
(getnext [_] next)
(setdata [_ node-data] (set! data node-data))
(setnext [_ next-ptr] (set! next next-ptr)))
(definterface ISinglyLinkedList
(gethead [])
(gettail [])
(sethead [list-head])
(settail [list-tail])
(insertnode [node-data]))
(deftype SinglyLinkedList [^:volatile-mutable head ^:volatile-mutable tail]
ISinglyLinkedList
(gethead [_] head)
(gettail [_] tail)
(sethead [_ list-head] (set! head list-head))
(settail [_ list-tail] (set! tail list-tail))
(insertnode [this node-data] [
(def node (SinglyLinkedListNode. node-data nil))
(if head [(.setnext (.gettail this) node)] (.sethead this node))
(.settail this node)]))
(defn print-singly-linked-list [node sep fptr]
(when node
[
(spit fptr (.getdata node) :append true)
(when (.getnext node) (spit fptr sep :append true))
(print-singly-linked-list (.getnext node) sep fptr)
]))
(defn print-list [list-head]
(loop [head list-head]
(if head (do
(prn (.getdata head))
(recur (.getnext head))))))
(def llist (SinglyLinkedList. nil nil))
(doseq [node-val [11 9 19 10 4]]
(.insertnode llist node-val)
)
(defn insert-node-at-position
"Complexity: O(n), where n is the size of the list"
[llist data position]
(loop [node llist p 0]
(if (> (dec position) p)
(recur (.getnext node) (inc p))
(.setnext node (SinglyLinkedListNode. data (.getnext node)))))
llist)
(insert-node-at-position (.gethead llist) 4 1)
(insert-node-at-position (.gethead llist) 20 3)
(print-list (.gethead llist))