public class StringLinkedListSelfContained
1: //If the file name is too long on your system, see the file StringLinkedListSelf.java
2:
3: public class StringLinkedListSelfContained
4: {
5: private ListNode head;
6:
7: public StringLinkedListSelf( )
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.data);
21: position = position.link;
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.link;
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(String addData)
45: {
46: head = new ListNode(addData, head);
47: }
48:
49: /**
50: Deletes the first node on the list.
51: */
52: public void deleteHeadNode( )
53: {
54: if (head != null)
55: head = head.link;
56: else
57: {
58: System.out.println("Deleting from an empty list.");
59: System.exit(0);
60: }
61: }
62:
63: /**
64: Sees whether target is on the list.
65: */
66: public boolean onList(String target)
67: {
68: return find(target) != null;
69: }
70:
71: // Returns a reference to the first node containing the
72: // target data. If target is not on the list, returns null.
73: private ListNode find(String target)
74: {
75: boolean found = false;
76: ListNode position = head;
77: while ((position != null) && !found)
78: {
79: String dataAtPosition = position.data;
80: if (dataAtPosition.equals(target))
81: found = true;
82: else
83: position = position.link;
84: }
85:
86: return position;
87: }
88:
89: public String[] toArray( )
90: {
91: String[] anArray = new String[length( )];
92:
93: ListNode position = head;
94: int i = 0;
95: while (position != null)
96: {
97: anArray[i] = position.data;
98: i++;
99: position = position.link;
100: }
101:
102: return anArray;
103: }
104:
105: private class ListNode
106: {
107: private String data;
108: private ListNode link;
109:
110: public ListNode( )
111: {
112: link = null;
113: data = null;
114: }
115:
116: public ListNode(String newData, ListNode linkValue)
117: {
118: data = newData;
119: link = linkValue;
120: }
121: }
122: }