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