1、用数组实现的stack,包括动态调整大小,可迭代,泛型
import java.util.*;
public class arraystack<item> implements Iterable<item> {
private item[] stack = (item[])new Object[1];
private int sizes=0;
private void resize(int len)
{
item[] new_stack=(item[])new Object[len];
for(int i=0;i<sizes;i++)
{
new_stack[i]=stack[i];
}
stack=new_stack;
}
public int size(){
return sizes;
}
public boolean isEmpty()
{
return sizes==0;
}
public void push(item data)
{
if(sizes==stack.length)
{
resize(sizes*2);
}
stack[sizes++]=data;
}
public item pop()
{
item a=stack[--sizes];
stack[sizes]=null;
if(sizes>0 && sizes==stack.length/4)
resize(stack.length/2);
return a;
}
public Iterator<item> iterator()
{
return new stackIterator();
}
private class stackIterator implements Iterator<item>
{
private int count=sizes;
public boolean hasNext()
{
return count>0;
}
public item next()
{
return stack[--count];
}
public void remove(){
}
}
}
2、链表实现stack
public class myStack<item> {
private int len;
private Node top;
public boolean isEmpty()
{
return len==0;
}
public int size()
{
return len;
}
public void push(item data)
{
Node old_top=top;
top=new Node();
top.data=data;
top.next=old_top;
len++;
}
public item pop()
{
item head_data=top.data;
top=top.next;
len--;
return head_data;
}
private class Node
{
item data;
Node next=null;
}
}
3、链表实现队列
public class myQueue<item> {
private int len;
Node head;
Node tail;
public boolean isEmpty()
{
return len==0;
}
public int size()
{
return len;
}
public void enQueue(item data)
{
Node old_tail=tail;
tail=new Node();
tail.data=data;
tail.next=null;
if(isEmpty())
{
head=tail;
}
else
{
old_tail.next=tail;
}
len++;
}
public item deQueue()
{
item data=head.data;
head=head.next;
if(isEmpty())
tail=null;
len--;
return data;
}
private class Node
{
item data;
Node next=null;
}
}