public class StringLinkedList
1:
2: public class StringLinkedList
3: {
4: private ListNode head;
5:
6: public StringLinkedList( )
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.getLink( );
22: }
23: return count;
24: }
25:
26: /**
27: Adds a node at the start of the list. The added node has addData
28: as its data. The added node will be the first node in the list.
29: */
30: public void addANodeToStart(String addData)
31: {
32: head = new ListNode(addData, head);
33: }
34:
35: public void deleteHeadNode( )
36: {
37: if (head != null)
38: {
39: head = head.getLink( );
40: }
41: else
42: {
43: System.out.println("Deleting from an empty list.");
44: System.exit(0);
45: }
46: }
47:
48: public boolean onList(String target)
49: {
50: return (Find(target) != null);
51: }
52:
53: /**
54: Finds the first node containing the target data and
55: returns a reference to that node.
56: If target is not in the list, null is returned.
57: */
58: private ListNode Find(String target)
59: {
60: ListNode position;
61: position = head;
62: String dataAtPosition;
63: while (position != null)
64: {
65: dataAtPosition = position.getData( );
66: if (dataAtPosition.equals(target))
67: return position;
68: position = position.getLink( );
69: }
70: //target was not found
71: return null;
72: }
73:
74: public void showList( )
75: {
76: ListNode position;
77: position = head;
78: while (position != null)
79: {
80: System.out.println(position.getData( ));
81: position = position.getLink( );
82: }
83: }
84: }