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