Groovy web console

subscribe to the feed Subscribe
to this
site

Linked List primer

Published 1 month ago by Anonymous with tags LInkedList Recursion
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
/* * * Linked List primer * * */

/**
 * Single list node
 */
class Node {
  def val
  Node next

  /** Empty Node */
  static final Node NIL = new Node(null, null)

  Node(def val, Node next = NIL) {
    this.val = val
    this.next = next
  }

  /** Recurse over all next nodes in this list*/
  private String toStringInternal() {
    ", ${val != null ? val : ''}${next.is(NIL) ? '' : next.toStringInternal()}"
  } 

  String toString() {
    if (this.is(NIL)) {
      "()"
    } else {
      "(${val != null ? val : ''}${next.is(NIL) ? '' : next.toStringInternal()})"
    }
  }
}

import static Node.NIL

/** 
 * List construction, LISP like.
 * Add new Node to the beginning of the List.
 */
Node cons(def x, Node next = NIL) {
  new Node(x, next)
}

/**
 * Append new Node to the end of the list.
 */
Node append(def x, Node lst) {
  if (lst.next.is(NIL)) {
    lst.next = new Node(x) //Append new Node to the end
  } else {
    append(x, lst.next) //Recurse till the list end
  }
  return lst
}

/** Recursive sum calculation */
def sum(Node lst, int res = 0) {
  if (lst.is(NIL)) {
    res
  } else {
    sum(lst.next, res + lst.val)
  }
}

/** Create list from variable arguments */
Node list(def ...args) {
    def lst = NIL
    for (int i = args.length - 1; i >= 0 ; i--) {
      lst = cons(args[i], lst)
    }
    lst
}

println NIL
println cons(1)

def lst = cons(1, cons(2, cons(3)))
println lst

def lst2 = cons(0, lst)
println lst2

def lst3 = append(4, lst2)
println lst3

println sum(lst3)
println sum(NIL)

println list(1, 2, 3, 4, 5)
println list()