-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenLL.java
133 lines (133 loc) · 2.42 KB
/
GenLL.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import java.util.Iterator;
public class GenLL <T> implements Iterable<T> //Generic type T
{
private class ListNode //Internal class
{
private T data;
private ListNode link;
public ListNode(T aData, ListNode aLink)
{
data = aData;
link = aLink;
}
}
private class ListIterator implements Iterator <T>
{
private ListNode iCurr;
public ListIterator(ListNode head)
{
iCurr = head;
}
public boolean hasNext()
{
return iCurr != null;
}
public T next()
{
T ret = iCurr.data;
iCurr = iCurr.link;
return ret;
}
}
public Iterator<T> iterator()
{
return new ListIterator(head);
}
private ListNode head; //Point to the first item in the list
private ListNode curr; //Current node of interest
private ListNode prev; //One node behind current
public GenLL()
{
head = curr = prev = null;
}
public void insert(T aData) //Inserts at the end of the list
{
ListNode newNode = new ListNode(aData, null);
if(head == null) //List is empty
{
head = newNode;
curr = head; //curr = newNode;
return;
}
ListNode temp = head;
while(temp.link != null)
{
temp = temp.link;
}
temp.link = newNode;
}
public void print()
{
for(ListNode temp = head; temp != null; temp = temp.link)
{
System.out.println(temp.data);
}
System.out.println();
}
public T getCurrent()
{
if(curr != null)
{
return curr.data;
}
return null;
}
public void setCurrent(T aData)
{
if(curr != null)
{
curr.data = aData;
}
}
public void goToNext()
{
if(curr == null)
{
return;
}
prev = curr;
curr = curr.link;
}
public void reset()
{
prev = null;
curr = head;
}
public void insertAfterCurren(T aData)
{
if(curr == null)
{
return;
}
ListNode newNode = new ListNode(aData, curr.link);
curr.link = newNode;
}
public void deleteCurrent()
{
if(curr != null && prev != null) //Current is not the head (in the middle)
{
prev.link = curr.link;
curr = curr.link;
}
else if(curr != null && prev == null) //Current is at the head
{
head = head.link; //curr = curr.link
}
}
public boolean isContained(T aData)
{
return search(aData) != null;
}
private ListNode search(T aData)
{
ListNode temp = head;
while(temp != null)
{
if(temp.data.equals(aData))
{
return temp;
}
}
return null;
}
}