import javax.swing.JOptionPane; /** * * @author Bill Kraynek */ public class Example7WithRecursion { /** * @param args the command line arguments */ public static void main(String[] args) { Node start = new Node("This", new Node("is", new Node("example", new Node("sentence", null)))); display(start); start.next.next = new Node("an", start.next.next); display(start); String[] inserts = {"example", "sentee", "This","This"}; for (String string : inserts) { if( start.data.equals(string) ) { start = new Node("insert", start); } else { insert(start,string); } display(start); }// end for }// end main static void insert(Node p, String data) { if( p.next == null ) { p.next = new Node("insert",null); return; }// end if if( p.next.data.equals(data) ) { p.next = new Node("insert",p.next); return; }// end if insert(p.next,data); } static void display(Node list) { Node p = list; String out = ""; while (p != null) { out += p.data + " "; p = p.next; }// end while out = out.substring(0, out.length() - 1) + ".\n"; out += "List = " + list + "\n"; JOptionPane.showMessageDialog(null, out); }// end display static class Node { String data; Node next; Node() { } Node(String data, Node next) { this.data = data; this.next = next; }// end constructor public String toString() { return "(" + data + " , " + next + ")"; }// end toString }// end Node } // end Example7WithRecursion