public class LinkedList
1:
2: import java.util.ArrayList;
3:
4: public class LinkedList<E>
5: {
6: private ListNode head;
7:
8: public LinkedList( )
9: {
10: head = null;
11: }
12:
13: public void showList( )
14: {
15: ListNode position = head;
16: while (position != null)
17: {
18: System.out.println(position.data);
19: position = position.link;
20: }
21: }
22:
23: public int length( )
24: {
25: int count = 0;
26: ListNode position = head;
27: while (position != null)
28: {
29: count++;
30: position = position.link;
31: }
32: return count;
33: }
34:
35: public void addANodeToStart(E addData)
36: {
37: head = new ListNode(addData, head);
38: }
39:
40: public void deleteHeadNode( )
41: {
42: if (head != null)
43: head = head.link;
44: else
45: {
46: System.out.println("Deleting from an empty list.");
47: System.exit(0);
48: }
49: }
50:
51: public boolean onList(E target)
52: {
53: return find(target) != null;
54: }
55:
56: private ListNode find(E target)
57: {
58: boolean found = false;
59: ListNode position = head;
60: while ((position != null) && !found)
61: {
62: E dataAtPosition = position.data;
63: if (dataAtPosition.equals(target))
64: found = true;
65: else
66: position = position.link;
67: }
68:
69: return position;
70: }
71:
72: public ArrayList<E> toArrayList( )
73: {
74: ArrayList<E> list = new ArrayList<E>(length( ));
75: ListNode position = head;
76: while (position != null)
77: {
78: list.add(position.data);
79: position = position.link;
80: }
81:
82: return list;
83: }
84:
85: private class ListNode
86: {
87: private E data;
88: private ListNode link;
89:
90: public ListNode( )
91: {
92: link = null;
93: data = null;
94: }
95:
96: public ListNode(E newData, ListNode linkValue)
97: {
98: data = newData;
99: link = linkValue;
100: }
101: }
102: }
103:
104:
105: