背包:
它是一种不支持从中删除元素的集合数据类型,目标就是帮助收集全部的元素,并且迭代遍历所有收集到的元素。迭代的顺序不确定,并且与用例无关。
主要的API:
Bag() 创建一个空的背包
void add(Item item) 添加一个元素
boolean isEmpty() 判断是否为空
int size() 背包中的数量
java实现:
链表:
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class Bag<Item> implements Iterable<Item> {
- // 背包的两个属性,一个是背包里面的数量,一个是背包里面的节点
- private int N;
- private Node<Item> first;
- private static class Node<Item> {
- private Item item;
- private Node<Item> next;
- }
- // 构造一个空的背包
- public Bag() {
- first = null;
- N = 0;
- }
- // 判断背包是否为空
- public boolean isEmpty() {
- return first == null;
- }
- // 背包的数量
- public int size() {
- return N;
- }
- // 背包的添加
- public void add(Item item) {
- Node<Item> oldfirst = first;
- first = new Node<Item>();
- first.item = item;
- first.next = oldfirst;
- N++;
- }
- // 实现迭代器接口的重写
- @Override
- public Iterator<Item> iterator() {
- return new ListIterator<Item>(first);
- }
- // 构建迭代器对象
- private class ListIterator<Item> implements Iterator<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;
- }
- }
- public static void main(String[] args) {
- Bag<String> bag = new Bag<String>();
- bag.add("aaa");
- bag.add("iii");
- for (String s : bag) {
- System.out.println(s);
- }
- }
- }
可变数组实现:
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class ResizingArrayBag<Item> implements Iterable<Item> {
- private Item[] a; // 空数组
- private int N = 0; // 背包元素数量
- /**
- * 创建一个空的背包
- */
- public ResizingArrayBag() {
- a = (Item[]) new Object[2];
- }
- /**
- * 背包是否为空
- * @return true 背包为空; false 相反
- */
- public boolean isEmpty() {
- return N == 0;
- }
- /**
- * 返回背包元素数量
- * @return the number of items in this bag
- */
- public int size() {
- return N;
- }
- // 创建一个数组,大小为capacity
- private void resize(int capacity) {
- assert capacity >= N;
- Item[] temp = (Item[]) new Object[capacity];
- for (int i = 0; i < N; i++)
- temp[i] = a[i];
- a = temp;
- }
- /**
- * 给背包中添加元素
- * @param item the item to add to this bag
- */
- public void add(Item item) {
- if (N == a.length) resize(2*a.length); // 如果N的数量等于给定数组大小的话就重新创建一个数组并且数组大小扩大一倍
- a[N++] = item; // 增加元素
- }
- /**
- * Returns an iterator that iterates over the items in the bag in arbitrary order.
- * @return an iterator that iterates over the items in the bag in arbitrary order
- */
- public Iterator<Item> iterator() {
- return new ArrayIterator();
- }
- // an iterator, doesn't implement remove() since it's optional
- private class ArrayIterator implements Iterator<Item> {
- private int i = 0;
- public boolean hasNext() { return i < N; }
- public void remove() { throw new UnsupportedOperationException(); }
- public Item next() {
- if (!hasNext()) throw new NoSuchElementException();
- return a[i++];
- }
- }
- /**
- * Unit tests the <tt>ResizingArrayBag</tt> data type.
- */
- public static void main(String[] args) {
- ResizingArrayBag<String> bag = new ResizingArrayBag<String>();
- bag.add("Hello");
- bag.add("World");
- bag.add("how");
- bag.add("are");
- bag.add("you");
- for (String s : bag)
- StdOut.println(s);
- }
- }
可以用来统计数字来进行计算。
=============================================================================
队列:
全称先进先出队列,按照任务产生的顺序完成他们的策略,基本上每天都会用到:典型就是排队。服务优先等待最久的人。
主要的API:
Queue() 创建一个空的队列
void enqueue(Item item) 添加一个元素
Item dequeue() 删除最早添加的元素
boolean isEmpty() 判断是否为空
int size() 队列中的数量
java代码实现:
链表:
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class LinkedQueue<Item> implements Iterable<Item> {
- private int N; // 队列元素的数量
- private Node first; // 第一个进去的元素
- private Node last; // 最后一个进去的元素
- // 链表类
- private class Node {
- private Item item;
- private Node next;
- }
- /**
- * 创建一个空的链表
- */
- public LinkedQueue() {
- first = null;
- last = null;
- N = 0;
- assert check();
- }
- /**
- * 判断链表是否为空
- *
- * @return true if this queue is empty; false otherwise
- */
- public boolean isEmpty() {
- return first == null;
- }
- /**
- * 返回链表的数量
- *
- * @return the number of items in this queue
- */
- public int size() {
- return N;
- }
- /**
- * 返回最近添加的元素
- *
- * @return the item least recently added to this queue
- * @throws java.util.NoSuchElementException
- * if this queue is empty
- */
- public Item peek() {
- if (isEmpty())
- throw new NoSuchElementException("Queue underflow");
- return first.item;
- }
- /**
- * 添加一个元素到队列中
- *
- * @param item
- * the item to add
- */
- 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;
- N++;
- assert check();
- }
- /**
- * 删除队列的第一个元素
- *
- * @return the item on this queue that was least recently added
- * @throws java.util.NoSuchElementException
- * if this queue is empty
- */
- public Item dequeue() {
- if (isEmpty())
- throw new NoSuchElementException("Queue underflow");
- Item item = first.item;
- first = first.next;
- N--;
- if (isEmpty())
- last = null; // to avoid loitering
- assert check();
- return item;
- }
- /**
- * 返回一个字符串这个队列的全部元素组成的
- *
- * @return the sequence of items in FIFO order, separated by spaces
- */
- public String toString() {
- StringBuilder s = new StringBuilder();
- for (Item item : this)
- s.append(item + " ");
- return s.toString();
- }
- // check internal invariants
- private boolean check() {
- if (N == 0) {
- if (first != null)
- return false;
- if (last != null)
- return false;
- } else if (N == 1) {
- if (first == null || last == null)
- return false;
- if (first != last)
- return false;
- if (first.next != null)
- return false;
- } else {
- if (first == last)
- return false;
- if (first.next == null)
- return false;
- if (last.next != null)
- return false;
- // check internal consistency of instance variable N
- int numberOfNodes = 0;
- for (Node x = first; x != null; x = x.next) {
- numberOfNodes++;
- }
- if (numberOfNodes != N)
- return false;
- // check internal consistency of instance variable last
- Node lastNode = first;
- while (lastNode.next != null) {
- lastNode = lastNode.next;
- }
- if (last != lastNode)
- return false;
- }
- return true;
- }
- /**
- * Returns an iterator that iterates over the items in this queue in FIFO
- * order.
- *
- * @return an iterator that iterates over the items in this queue in FIFO
- * order
- */
- public Iterator<Item> iterator() {
- return new ListIterator();
- }
- // an iterator, doesn't implement remove() since it's optional
- private class ListIterator implements Iterator<Item> {
- private Node 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;
- }
- }
- }
数组:
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class ResizingArrayQueue <Item> implements Iterable<Item>{
- private Item[] q; // queue elements
- private int N = 0; // number of elements on queue
- private int first = 0; // index of first element of queue
- private int last = 0; // index of next available slot
- /**
- * Initializes an empty queue.
- */
- public ResizingArrayQueue() {
- // cast needed since no generic array creation in Java
- q = (Item[]) new Object[2];
- }
- /**
- * Is this queue empty?
- *
- * @return true if this queue is empty; false otherwise
- */
- public boolean isEmpty() {
- return N == 0;
- }
- /**
- * Returns the number of items in this queue.
- *
- * @return the number of items in this queue
- */
- public int size() {
- return N;
- }
- // resize the underlying array
- private void resize(int max) {
- assert max >= N;
- Item[] temp = (Item[]) new Object[max];
- for (int i = 0; i < N; i++) {
- temp[i] = q[(first + i) % q.length];
- }
- q = temp;
- first = 0;
- last = N;
- }
- /**
- * Adds the item to this queue.
- *
- * @param item
- * the item to add
- */
- public void enqueue(Item item) {
- // double size of array if necessary and recopy to front of array
- if (N == q.length)
- resize(2 * q.length); // double size of array if necessary
- q[last++] = item; // add item
- if (last == q.length)
- last = 0; // wrap-around
- N++;
- }
- /**
- * Removes and returns the item on this queue that was least recently added.
- *
- * @return the item on this queue that was least recently added
- * @throws java.util.NoSuchElementException
- * if this queue is empty
- */
- public Item dequeue() {
- if (isEmpty())
- throw new NoSuchElementException("Queue underflow");
- Item item = q[first];
- q[first] = null; // to avoid loitering
- N--;
- first++;
- if (first == q.length)
- first = 0; // wrap-around
- // shrink size of array if necessary
- if (N > 0 && N == q.length / 4)
- resize(q.length / 2);
- return item;
- }
- /**
- * Returns the item least recently added to this queue.
- *
- * @return the item least recently added to this queue
- * @throws java.util.NoSuchElementException
- * if this queue is empty
- */
- public Item peek() {
- if (isEmpty())
- throw new NoSuchElementException("Queue underflow");
- return q[first];
- }
- /**
- * Returns an iterator that iterates over the items in this queue in FIFO
- * order.
- *
- * @return an iterator that iterates over the items in this queue in FIFO
- * order
- */
- public Iterator<Item> iterator() {
- return new ArrayIterator();
- }
- // an iterator, doesn't implement remove() since it's optional
- private class ArrayIterator implements Iterator<Item> {
- private int i = 0;
- public boolean hasNext() {
- return i < N;
- }
- public void remove() {
- throw new UnsupportedOperationException();
- }
- public Item next() {
- if (!hasNext())
- throw new NoSuchElementException();
- Item item = q[(i + first) % q.length];
- i++;
- return item;
- }
- }
- public static void main(String[] args) {
- ResizingArrayQueue<String>s=new ResizingArrayQueue<String>();
- s.enqueue("ppppp");
- s.enqueue("eeee");
- System.out.println(s.dequeue());
- }
- }
栈:
下压栈 ,后进先出,好比浏览网页,的后退键等。
java实现:
链表:
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- import java.util.Stack;
- public class LinkedStack<Item> implements Iterable<Item> {
- private int N;
- private Node first;
- private class Node {
- private Item item;
- private Node next;
- }
- public LinkedStack() {
- first = null;
- N = 0;
- assert check();
- }
- public boolean isEmpty() {
- return first == null;
- }
- public int size() {
- return N;
- }
- public void push(Item item) {
- Node oldfirst = first;
- first = new Node();
- first.next = oldfirst;
- first.item = item;
- N++;
- assert check();
- }
- public Item pop() {
- if (isEmpty()) {
- throw new NoSuchElementException("Stack underflow");
- }
- Item item = first.item;
- first = first.next;
- N--;
- assert check();
- return item;
- }
- public Item peak() {
- if (isEmpty())
- throw new NoSuchElementException("Queue underflow");
- return first.item;
- }
- public String toString() {
- StringBuilder s = new StringBuilder();
- // for (Item item : this)
- // s.append(item + " ");
- for (Node x =first; x!=null; x=x.next) {
- s.append(x.item + " ");
- }
- return s.toString();
- }
- private boolean check() {
- if (N==0) {
- if (first==null) {
- return false;
- }else if (N==1) {
- if (first==null) {
- return false;
- }
- if (first.next!=null) {
- return false;
- }
- }else {
- if (first.next==null) {
- return false;
- }
- }
- }
- int numberOfNodes = 0;
- for (Node x = first; x != null; x = x.next) {
- numberOfNodes++;
- }
- if (numberOfNodes != N) return false;
- return true;
- }
- @Override
- public Iterator<Item> iterator() {
- // TODO Auto-generated method stub
- return new ListIterator();
- }
- private class ListIterator implements Iterator<Item> {
- private Node 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;
- }
- }
- public static void main(String[] args) {
- LinkedStack<String>s=new LinkedStack<String>();
- Stack<Character>a=new Stack<Character>();
- a.peek();
- }
- }
数组实现:
-
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class ResizingArrayStack<Item> implements Iterable<Item> {
- private Item[] a;
- private int N;
- public ResizingArrayStack() {
- a = (Item[]) new Object[2];
- }
- public boolean isEmpty() {
- return N == 0;
- }
- public int size() {
- return N;
- }
- private void resize(int cap) {
- assert cap >= N;
- Item[] temp = (Item[]) new Object[cap];
- for (int i = 0; i < N; i++) {
- temp[i] = a[i];
- }
- a = temp;
- }
- public void push(Item item) {
- if (N == a.length) {
- resize(2 * a.length);
- }
- a[N++] = item;
- }
- public Item pop() {
- if (isEmpty()) {
- throw new NoSuchElementException("Stack underflow");
- }
- Item item = a[N - 1];
- a[N - 1] = null;
- N--;
- if (N > 0 && N == a.length / 4) {
- resize(a.length / 2);
- }
- return item;
- }
- public Item peek() {
- if (isEmpty())
- throw new NoSuchElementException("Stack underflow");
- return a[N - 1];
- }
- @Override
- public Iterator<Item> iterator() {
- return new ReverseArrayIterator();
- }
- private class ReverseArrayIterator implements Iterator<Item> {
- private int i;
- public ReverseArrayIterator() {
- i = N - 1;
- }
- public boolean hasNext() {
- return i >= 0;
- }
- public void remove() {
- throw new UnsupportedOperationException();
- }
- public Item next() {
- if (!hasNext())
- throw new NoSuchElementException();
- return a[i--];
- }
- }
- public static void main(String[] args) {
- ResizingArrayStack<String> s = new ResizingArrayStack<String>();
- s.push("kk");
- s.push("pp");
- s.push("pp");
- s.push("pp");
- System.out.println(s.pop());
- System.out.println(s.pop());
- System.out.println(s.pop());
- System.out.println(s.pop());
- System.out.println(s.N);
- }
- }