链表实现bag stack queue数据结构

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;
			}
		};
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值