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