-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.java
53 lines (42 loc) · 1.14 KB
/
Stack.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
// Implemented with a singly-linked-list. I may add a
// separate implementation with ArrayLists or Vectors.
// Uses null value as an end-signifier.
import java.util.Iterator;
public class Stack<T> {
private Node head = null;
private class Node {
T data;
Node next;
}
public void push(T item) {
Node temp = head;
head = new Node();
head.next = temp;
head.data = item;
}
public T pop() {
if (head == null) { return null; }
T item = head.data;
head = head.next;
return item;
}
public boolean isEmpty() {
return head == null;
}
public Iterator<T> iterator() {
return new StackIterator();
}
private class StackIterator implements Iterator<T> {
private Node current = head;
public boolean hasNext() {
return current != null;
}
public void remove() {/* unsupported, does nothing */}
public T next() {
if (current == null) { return null; }
T item = current.data;
current = current.next;
return item;
}
}
}