// Written by: Darren Gates & Ray Klefstad // Date: January 2000 // School: U.C. Irvine import java.awt.*; import java.applet.*; public class LinkedListsExample extends Applet { private TextArea display; public void init() { display = new TextArea(8, 35); add(display); String result = ""; LinkedList myList = new LinkedList(); myList.insert("list."); myList.insert("my"); myList.insert("is"); myList.insert("This"); result += myList.toString() + "\n"; int found1 = myList.find("hello"); int found2 = myList.find("This"); int found3 = myList.find("list."); result += "Now testing find method (-1 if not found)...\n\n"; result += "'hello' is found at position: " + found1 + "\n"; result += "'list.' is found at position: " + found3 + "\n"; result += "'This' is found at position: " + found2 + ""; display.setText(result); } } class LinkedList { public static class Node { private Object info; private Node next; public Node(Object newInfo, Node newNext) { info = newInfo; next = newNext; } } private Node head; public LinkedList() { head = null; } public void insert(Object info) { head = new Node(info, head); } public int find(Object info) { int i = 0; for (Node cur = head; cur != null; cur = cur.next, i++) { if (info.equals(cur.info)) return i; } return -1; // not found } public String toString() { String result = ""; for (Node cur = head; cur != null; cur = cur.next) result += cur.info + " "; return result; } }