Thursday, May 29, 2014

Simple Linked List

class Node implements Cloneable {
    private int val
    private int i
    private Node prev
    private Node next
    
    private static Node head
    private static Node last
    
    Node(int val, int i = 0) {
        if (!head) head = this
        if (!last) last = this
        
        this.i = i
        this.val = val
    }
    
    Integer at(int x, Node node = this) {
        //println "" + x + node.i + node.next
        
        if (x > node.i) {
            if (node.next != null) 
                return this.at(x, node.next)
            else 
                return null
        }

        return node.val
    }
    
    Node add(int val) {
        Node newNode = new Node(val, last.i + 1)
        
        newNode.prev = last
        last.next = newNode
        
        last = newNode
        
        //println "---\nadd done\n---"
        
        return head
    }
    
    Node reverse() {
        Node r = last.clone()
        Node prev = last.prev
        
        while (prev != null) {
            r.add(prev.val)
            prev = prev.prev    
        }
        
        return r
    }
}



Node list = new Node(1)

assert list.at(0) == 1

list.add(4).add(6) // chained adding

assert list.at(0) == 1

assert list.at(1) == 4

assert list.at(2) == 6

assert list.at(3) == null

assert list.reverse().at(0) == list.at(2)

No comments:

Post a Comment