public class StringLinkedList
1: //StringLinkedList.java
2:
3: public class StringLinkedList
4: {
5: private ListNode head;
6:
7: public StringLinkedList()
8: {
9: head = null;
10: }
11:
12: /**
13: * Displays the data on the list.
14: */
15: public void showList()
16: {
17: ListNode position = head;
18: while (position != null)
19: {
20: System.out.println(position.getData());
21: position = position.getLink();
22: }
23: }
24:
25: /**
26: * Returns the number of nodes on the list.
27: */
28: public int length()
29: {
30: int count = 0;
31: ListNode position = head;
32: while (position != null)
33: {
34: count++;
35: position = position.getLink();
36: }
37: return count;
38: }
39:
40: /**
41: * Adds a node containing the data addData at the
42: * start of the list.
43: */
44: public void addANodeToStart
45: (
46: String addData
47: )
48: {
49: head = new ListNode(addData, head);
50: }
51:
52: /**
53: * Deletes the first node on the list.
54: */
55: public void deleteHeadNode()
56: {
57: if (head != null)
58: {
59: head = head.getLink();
60: }
61: else
62: {
63: System.out.println("Deleting from an empty list.");
64: System.exit(0);
65: }
66: }
67:
68: /**
69: * Sees whether target is on the list.
70: */
71: public boolean onList(String target)
72: {
73: return find(target) != null;
74: }
75:
76: //Returns a reference to the first node containing the
77: //target data. If target is not on the list, returns null.
78: private ListNode find
79: (
80: String target
81: )
82: {
83: boolean found = false;
84: ListNode position = head;
85: while ((position != null) && !found)
86: {
87: String dataAtPosition = position.getData();
88: if (dataAtPosition.equals(target))
89: found = true;
90: else
91: position = position.getLink();
92: }
93: return position;
94: }
95: }