Repository navigation
Expand file tree
/
Copy pathSimpleLinkedStack.java
More file actions
103 lines (89 loc) · 2.33 KB
/
Copy pathSimpleLinkedStack.java
File metadata and controls
103 lines (89 loc) · 2.33 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
package stack;
import java.util.EmptyStackException;
import java.util.Iterator;
public class SimpleLinkedStack<V> implements SimpleStack<V>, Iterable<V> {
private Node<V> lastNode = null;
private int size = 0;
@Override
public int getSize(){
return size;
}
@Override
public boolean put(V value) {
Node<V> newNode = new Node(value);
newNode.setAhead(lastNode);
lastNode = newNode;
size++;
return true;
}
@Override
public V pop(){
if(lastNode != null) {
if (lastNode.ahead == null) {
Node<V> returnNode = lastNode;
lastNode = null;
size--;
return returnNode.getValue();
}
else{
Node<V> returnNode = lastNode;
Node newLastNode = lastNode.ahead;
lastNode = newLastNode;
size--;
return returnNode.getValue();
}
}
throw new EmptyStackException();
}
@Override
public V peek() {
if(lastNode != null) {
if (lastNode.ahead == null) {
return lastNode.value;
} else {
return lastNode.getValue();
}
}
throw new EmptyStackException();
}
@Override
public Iterator<V> iterator() {
return new Iterator<V>() {
Node cursor = lastNode;
@Override
public boolean hasNext() {
if(cursor != null){
return true;
}
else {
return false;
}
}
@Override
public V next() {
if (hasNext()) {
V value = (V) cursor.getValue();
cursor = cursor.getAheadNode();
return value;
}
return null;
}
};
}
private class Node<V> {
Node ahead;
V value;
Node(V newValue) {
this.value = newValue;
}
private Node getAheadNode() {
return ahead;
}
private void setAhead(Node ahead) {
this.ahead = ahead;
}
private V getValue() {
return value;
}
}
}