queue&stack
This commit is contained in:
1 parent
92cadc5de9
commit
7e9ca52fa0
2 files changed
+136
No files matched your search
@@ -0,0 +1,60 @@
|
||||
import java.util.Iterator;
|
||||
|
||||
public class Stack<Item> implements Iterable<Item> {
|
||||
private Node first;
|
||||
private int N;
|
||||
|
||||
private class Node {
|
||||
Item item;
|
||||
Node next;
|
||||
}
|
||||
|
||||
public void push(Item item) {
|
||||
Node oldfirst = first;
|
||||
first = new Node();
|
||||
first.item = item;
|
||||
first.next = oldfirst;
|
||||
N++;
|
||||
}
|
||||
|
||||
public Item pop() {
|
||||
Item item = first.item;
|
||||
first = first.next;
|
||||
N--;
|
||||
return item;
|
||||
}
|
||||
|
||||
public Iterator<Item> iterator() {
|
||||
return new ReverseArrayIterator();
|
||||
}
|
||||
|
||||
private class ReverseArrayIterator implements Iterator<Item> {
|
||||
private int i = N;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return i > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Item next() {
|
||||
Node nextnode = first;
|
||||
for (int j = 0; j < N - i; j++)
|
||||
nextnode = nextnode.next;
|
||||
i--;
|
||||
return nextnode.item;
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Stack<Integer> s = new Stack<Integer>();
|
||||
s.push(1);
|
||||
s.push(2);
|
||||
s.push(3);
|
||||
for (int i : s)
|
||||
System.out.println(i);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user