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