import java.util.Iterator;
/*
* 背包bag是一种不支持删除元素的集合数据结构,它的目的是为了收集
* 元素并迭代遍历所收集到的元素,以下是用链表实现的bag的API
* 集合中的元素使用了泛型Item
* 实现Iterable接口可以使得bag集合能用foreach迭代
* */
public class Bag<Item> implements Iterable<Item>{
private Node first;//链表首节点
private int count;//节点数
//定义内部节点类
private class Node{
Item item;//泛型数据
Node next;//下个节点
}
@Override
public Iterator<Item> iterator() {
return new Iterator<Item>(){
private Node current=first;
public boolean hasNext() {
return current!=null;
}
public Item next() {
Item temp=current.item;
current=current.next;
return temp;
}
};
}
//在表头插入一个节点
public void add(Item item){
Node oldfirst=first;
first=new Node();
first.item=item;
first.next=oldfirst;
count++;
}
//判断链表是否为空
public boolean isEmpty(){
return count==0;
}
//获取链表节点个数
public int size(){
return count;
}
}
import java.util.Iterator;
/*
* 栈Stack遵循LIFO(后进先出)
* push时在链表头添加一个节点
* pop时在链表头删除一个节点
* */
public class Stack<Item> implements Iterable<Item>{
private Node first;//首节点
private int count;//数量
//节点类
private class Node{
Item item;
Node next;
}
public void push(Item item){
Node oldfirst=first;
first=new Node();
first.item=item;
first.next=oldfirst;
count++;
}
public Item pop(){
Item item=first.item;
first=first.next;
count--;
return item;
}
public boolean isEmpty(){
return count==0;
}
public int size(){
return count;
}
@Override
public Iterator<Item> iterator() {
return new Iterator<Item>(){
private Node current=first;
public boolean hasNext() {
return current!=null;
}
public Item next() {
Item item=current.item;
current=current.next;
return item;
}
};
}
}
import java.util.Iterator;
/*
* 队列遵循先进先出
* 入队时在表尾添加一个节点
* 出队时在表头删除一个节点
* */
public class Queue<Item> implements Iterable<Item>{
private Node first;//首节点
private Node last;//尾节点
private int count;//个数
private class Node{
Item item;
Node next;
}
public void enqueue(Item item){
Node oldlast=last;
last=new Node();
last.item=item;
last.next=null;
if(isEmpty()){
first=last;
}else{
oldlast.next=last;
}
count++;
}
public Item dequeue(){
Item item=first.item;
first=first.next;
count--;
return item;
}
public int size(){
return count;
}
public boolean isEmpty(){
return count==0;
}
@Override
public Iterator<Item> iterator() {
return new Iterator<Item>(){
private Node current=first;
public boolean hasNext() {
return current!=null;
}
public Item next() {
Item item=current.item;
current=current.next;
return item;
}
};
}
}