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