-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoWayLinkedList.java
More file actions
140 lines (117 loc) · 2.69 KB
/
Copy pathTwoWayLinkedList.java
File metadata and controls
140 lines (117 loc) · 2.69 KB
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
134
135
136
137
138
139
140
import java.util.Iterator;
/* Struktura danych: gąsienica cykliczna
* Autor: Grzegorz Myjak
*/
public class TwoWayLinkedList <T> implements Iterable<T>
{
private class Element
{
private T value;
private Element next;
private Element previous;
public Element (T value)
{
this.value = value;
}
public Element getNext()
{
return next;
}
public Element getPrevious()
{
return previous;
}
public T getValue()
{
return value;
}
public void setNext(Element e)
{
next = e;
}
public void setPrevious(Element e)
{
previous = e;
}
public void insertAfter(T value)
{
Element temp = new Element(value);
temp.setPrevious(this);
temp.setNext(getNext());
getNext().setPrevious(temp);
setNext(temp);
}
public void insertBefore(T value)
{
Element temp = new Element(value);
temp.setPrevious(getPrevious());
temp.setNext(this);
getPrevious().setNext(temp);
setPrevious(temp);
}
public T remove()
{
getPrevious().setNext(getNext());
getNext().setPrevious(getPrevious());
return getValue();
}
}
private Element sentinel;
public TwoWayLinkedList()
{
sentinel = new Element(null);
sentinel.setNext(sentinel);
sentinel.setPrevious(sentinel);
}
public void addHead(T value)
{
sentinel.insertAfter(value);
}
public void addTail(T value)
{
sentinel.insertBefore(value);
}
public T getHead()
{
return sentinel.getNext().getValue();
}
public T getTail()
{
return sentinel.getPrevious().getValue();
}
public T cutTail()
{
return sentinel.getPrevious().remove();
}
@Override
public Iterator<T> iterator()
{
return new ListIterator();
}
private class ListIterator implements Iterator
{
private Element current;
public ListIterator()
{
current = sentinel;
}
@Override
public boolean hasNext()
{
if (current.getNext().getValue() != null)
{
return true;
}
else
{
return false;
}
}
@Override
public T next()
{
current = current.getNext();
return current.getValue();
}
}
}