// Linked lists in Java, first version: A lot of code was added to this // file, so it's now longer than the C++ version. class node { int head; node tail; node(int h, node t) // constructor { head=h; tail=t; } boolean member(int x) // determine if x is in list { node i = this; boolean answer = false; while (i!=null && !answer) { if (i.head == x) answer = true; i = i.tail; } return answer; } /* alternative, recursive definition of member: */ boolean memb(int x) { return x==head || (tail!=null && tail.memb(x)); } int length() { if (tail==null) return 1; else return 1+tail.length(); } // static version static int length(node n) { if (n==null) return 0; else return 1+length(n.tail); } void add(int x) // add new integer to end of list { node i = this; while (i.tail != null) i = i.tail; i.tail = new node(x,null); } int get(int n) throws Exception // get nth element starting from this node { node i = this; for(;n>0 && i!=null; i=i.tail, n--); if (i == null) throw new Exception("index out of bounds"); else return i.head; } } // class node public class first { public static void main(String[] argv) { node N = new node(2, new node(4, new node(6, null))); N.add(8); System.out.println("the third element is "+N.get(2)); System.out.println(N.memb(5)); } } // class first