/** Implementation of a generic linked list. @author Jed Yang, 2018-04-27 */ public class CarlLinkedList implements List { private static class Node { private E data; private Node next; public Node(E data) { this(data, null); } public Node(E data, Node nextNode) { this.data = data; this.next = nextNode; } } // instance variables, private private Node head; public CarlLinkedList() { head = null; } /** Live-code. */ public void add(E item) { if (head == null) { head = new Node(item); } else { Node cur = head; while (cur.next != null) { cur = cur.next; } cur.next = new Node(item); } } /** Worksheet. */ public void add(int index, E item) { } public E get(int index) { return null; } public int size() { return -1; } /** Returns a comma-separated list of the elements. @return string representation */ public String toString() { return "[" + toStringRecursive(head) + "]"; } /** Constructs string representation starting at node. */ private String toStringRecursive(Node node) { if (node == null) // 0 elements { return ""; } else if (node.next == null) // 1 element { return "" + node.data; } else { return node.data + ", " + toStringRecursive(node.next); // return "" + toStringRecursive(node.next) + ", " + node.data; // in reverse! } } /** Iterative version of toString; using StringBuilder for efficiency. */ public String toStringIterative() { StringBuilder str = new StringBuilder("["); Node cur = head; while (cur != null) { str.append(cur.data); if (cur.next != null) str.append(", "); cur = cur.next; } str.append("]"); return str.toString(); } /** Demo and test of List methods. */ public static void main(String[] args) { List list1 = new CarlLinkedList(); for (int i = 0; i < 4; i++) { list1.add(i); } System.out.println("list1 should be [0, 1, 2, 3]; actually: " + list1); System.out.println("length should be 4; actually: " + list1.size()); System.out.println("==============================================="); List list2 = new CarlLinkedList(); list2.add(0, "a"); list2.add(1, "c"); list2.add(1, "b"); list2.add(3, "d"); System.out.println("list2 should be [a, b, c, d]; actually: " + list2); System.out.println("length should be 4; actually: " + list2.size()); } }