queue&stack

This commit is contained in:
2018-06-04 21:41:27 +08:00
parent 92cadc5de9
commit 7e9ca52fa0
2 changed files with 136 additions and 0 deletions
+76
View File
@@ -0,0 +1,76 @@
import edu.princeton.cs.introcs.StdOut;
import java.util.Iterator;
public class Queue<Item> implements Iterable<Item>
{
private Node first;
private Node last;
private int N;
private class Node
{
Item item;
Node next;
}
public boolean isEmpty() {return first==null;}
public int size() {return N;}
public void enqueue(Item item)
{
// last.next = new Node();
// last = last.next;
// last.item = item;
// N++;
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if(isEmpty()) first = last;
else oldlast.next = last;
N++;
}
public Item dequeue()
{
Item item = first.item;
first = first.next;
if(isEmpty()) last = null;
N--;
return item;
}
public Iterator<Item> iterator()
{
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item>
{
int i = 0;
Node nextnode = first;
@Override
public boolean hasNext() {
return i<N;
}
@Override
public Item next() {
if(i!=0)
nextnode = nextnode.next;
i++;
return nextnode.item;
}
@Override
public void remove() {
}
}
public static void main(String[] args)
{
Queue<Integer> q = new Queue<Integer>();
q.enqueue(1);
q.enqueue(2);
q.enqueue(5);
for(int i:q)
StdOut.println(i);
}
}
+60
View File
@@ -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);
}
}