算法(第四版)——背包

继续复习之前看过的内容......


背包


背包的定义

 背包是一种不支持从中删除元素的集合数据类型,目的是帮助用例收集元素并迭代所有收集到的元素,也是检查背包是否为空,或者获取背包中元素的数量。

背包的实现 

import java.util.Iterator;
//定义泛型背包类
public class Bag<Item> implements Iterable<Item>{
	private Node<Item> first;   // 背包的开始
	private int n; 				// 背包中元素的个数
	
	//背包节点类
	private class Node<Item> {
		Item item; //参数
		Node next; // 
	}
	/**
	* 初始化空背包
	*/
	public Bag() {
		first = null;
		n = 0;
	}
	
	/**
	* 如果背包为空返回True
	*
	* @return {@code true} 如果背包为空
	* @return {@code false} 否则
	*/
	public boolean isEmpty() {
		return first == null;
	}
	
	/**
	* 返回背包中元素的个数
	*
	* @return 背包中元素的个数
	*/
	public int size() {
		return n;
	}
	
	/**
	* 添加 item 到背包
	*
	* @param 被添加进背包的item
	*/
	public void add(Item item) {
		Node<Item> oldFirst = first;
		first = new Node<Item>();
		fitst.item = item;
		first.next = oldFirst;
		n++;
	}
	
	/**
	* 返回一个迭代器,该迭代器按任意顺序遍历袋子中的项。
	*
	* @return 一个迭代器,它以任意顺序遍历这个袋子中的项
	*/
	public Iterator iterator() {
		return new ListIterator<Item>(first);
	}
	
	// 迭代器,没有实现remove(),因为它是可选的
	private class ListIterator<Item> {
		private Node<Item> current;
		
		public ListIterator(Node<Item> first) {
			current = first;
		}
		
		public boolean hasNext() {return current != null;}
		public void remove()     {throw new UnsupportedOperationException();}
		
		public Item next() {
			 if (!hasNext()) throw new NoSuchElementException();
			 Item item  = current.item;
			 current = current.next;
			 return item;
		}
	}
	
    /**
     * 单元测试 {@code Bag} 数据类型。
     *
     * @param args the command-line arguments
     */
	public static void main(String[] args) {
        Bag<String> bag = new Bag<String>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            bag.add(item);
        }
 
        StdOut.println("size of bag = " + bag.size());
        for (String s : bag) {
            StdOut.println(s);
        }
    }
}

以上代码按照 Robert Sedgewick的源码的结构编写,大师的代码看起来就是舒服。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值