public class StringLinkedListSelfContained
1: //StringLinkedListSelfContained.java
2:
3: public class StringLinkedListSelfContained
4: {
5: private ListNode head;
6:
7: //public StringLinkedListSelf()
8: public StringLinkedListSelfContained()
9: {
10: head = null;
11: }
12:
13: /**
14: * Displays the data on the list.
15: */
16: public void showList()
17: {
18: ListNode position = head;
19: while (position != null)
20: {
21: System.out.println(position.data);
22: position = position.link;
23: }
24: }
25:
26: /**
27: * Returns the number of nodes on the list.
28: */
29: public int length()
30: {
31: int count = 0;
32: ListNode position = head;
33: while (position != null)
34: {
35: count++;
36: position = position.link;
37: }
38: return count;
39: }
40:
41: /**
42: * Adds a node containing the data addData at the
43: * start of the list.
44: */
45: public void addANodeToStart
46: (
47: String addData
48: )
49: {
50: head = new ListNode(addData, head);
51: }
52:
53: /**
54: * Deletes the first node on the list.
55: */
56: public void deleteHeadNode()
57: {
58: if (head != null)
59: head = head.link;
60: else
61: {
62: System.out.println("Deleting from an empty list.");
63: System.exit(0);
64: }
65: }
66:
67: /**
68: * Sees whether target is on the list.
69: */
70: public boolean onList(String target)
71: {
72: return find(target) != null;
73: }
74:
75: //Returns a reference to the first node containing the
76: //target data. If target is not on the list, returns null.
77: private ListNode find
78: (
79: String target
80: )
81: {
82: boolean found = false;
83: ListNode position = head;
84: while ((position != null) && !found)
85: {
86: String dataAtPosition = position.data;
87: if (dataAtPosition.equals(target))
88: found = true;
89: else
90: position = position.link;
91: }
92: return position;
93: }
94:
95: public String[] toArray()
96: {
97: String[] anArray = new String[length()];
98:
99: ListNode position = head;
100: int i = 0;
101: while (position != null)
102: {
103: anArray[i] = position.data;
104: i++;
105: position = position.link;
106: }
107: return anArray;
108: }
109:
110: private class ListNode
111: {
112: private String data;
113: private ListNode link;
114:
115: public ListNode()
116: {
117: link = null;
118: data = null;
119: }
120:
121: public ListNode
122: (
123: String newData,
124: ListNode linkValue
125: )
126: {
127: data = newData;
128: link = linkValue;
129: }
130: }
131: }