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