码迷,mamicode.com
首页 > 系统相关 > 详细

algorithms第四版学习进程(一)背包,栈,队列

时间:2015-06-22 16:16:04      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

背包:

它是一种不支持从中删除元素的集合数据类型,目标就是帮助收集全部的元素,并且迭代遍历所有收集到的元素。迭代的顺序不确定,并且与用例无关。

主要的API:

      Bag()              创建一个空的背包

void        add(Item item)     添加一个元素

boolean   isEmpty()        判断是否为空

int      size()           背包中的数量

java实现:

链表:

  1. import java.util.Iterator;
  2. import java.util.NoSuchElementException;
  3. public class Bag<Item> implements Iterable<Item> {
  4.      // 背包的两个属性,一个是背包里面的数量,一个是背包里面的节点
  5.      private int N;
  6.      private Node<Item> first;
  7.      private static class Node<Item> {
  8.           private Item item;
  9.           private Node<Item> next;
  10.      }
  11.      // 构造一个空的背包
  12.      public Bag() {
  13.           first = null;
  14.           N = 0;
  15.      }
  16.      // 判断背包是否为空
  17.      public boolean isEmpty() {
  18.           return first == null;
  19.      }
  20.      // 背包的数量
  21.      public int size() {
  22.           return N;
  23.      }
  24.      // 背包的添加
  25.      public void add(Item item) {
  26.           Node<Item> oldfirst = first;
  27.           first = new Node<Item>();
  28.           first.item = item;
  29.           first.next = oldfirst;
  30.           N++;
  31.      }
  32.      // 实现迭代器接口的重写
  33.      @Override
  34.      public Iterator<Item> iterator() {
  35.           return new ListIterator<Item>(first);
  36.      }
  37.      // 构建迭代器对象
  38.      private class ListIterator<Item> implements Iterator<Item> {
  39.           // 迭代器里面有一个属性节点
  40.           private Node<Item> current;
  41.           // 构造器
  42.           public ListIterator(Node<Item> first) {
  43.                current = first;
  44.           }
  45.           // 判断是否迭代完成
  46.           public boolean hasNext() {
  47.                return current != null;
  48.           }
  49.           // 移除
  50.           public void remove() {
  51.                throw new UnsupportedOperationException();
  52.           }
  53.           // 迭代下一个
  54.           public Item next() {
  55.                if (!hasNext())
  56.                     throw new NoSuchElementException();
  57.                Item item = current.item;
  58.                current = current.next;
  59.                return item;
  60.           }
  61.      }
  62.      public static void main(String[] args) {
  63.           Bag<String> bag = new Bag<String>();
  64.           bag.add("aaa");
  65.           bag.add("iii");
  66.           for (String s : bag) {
  67.                System.out.println(s);
  68.           }
  69.      }
  70. }

可变数组实现:

  1. import java.util.Iterator;
  2. import java.util.NoSuchElementException;
  3. public class ResizingArrayBag<Item> implements Iterable<Item> {
  4.     private Item[] a;         // 空数组
  5.     private int N = 0;        // 背包元素数量
  6.     /**
  7.      * 创建一个空的背包
  8.      */
  9.     public ResizingArrayBag() {
  10.         a = (Item[]) new Object[2];
  11.     }
  12.     /**
  13.      * 背包是否为空
  14.      * @return true 背包为空; false 相反
  15.      */
  16.     public boolean isEmpty() {
  17.         return N == 0;
  18.     }
  19.     /**
  20.      * 返回背包元素数量
  21.      * @return the number of items in this bag
  22.      */
  23.     public int size() {
  24.         return N;
  25.     }
  26.     // 创建一个数组,大小为capacity
  27.     private void resize(int capacity) {
  28.         assert capacity >= N;
  29.         Item[] temp = (Item[]) new Object[capacity];
  30.         for (int i = 0; i < N; i++)
  31.             temp[i] = a[i];
  32.         a = temp;
  33.     }
  34.     /**
  35.      * 给背包中添加元素
  36.      * @param item the item to add to this bag
  37.      */
  38.     public void add(Item item) {
  39.         if (N == a.length) resize(2*a.length);    // 如果N的数量等于给定数组大小的话就重新创建一个数组并且数组大小扩大一倍
  40.         a[N++] = item;                            // 增加元素
  41.     }
  42.     /**
  43.      * Returns an iterator that iterates over the items in the bag in arbitrary order.
  44.      * @return an iterator that iterates over the items in the bag in arbitrary order
  45.      */
  46.     public Iterator<Item> iterator() {
  47.         return new ArrayIterator();
  48.     }
  49.     // an iterator, doesn‘t implement remove() since it‘s optional
  50.     private class ArrayIterator implements Iterator<Item> {
  51.         private int i = 0;
  52.         public boolean hasNext()  { return i < N;                               }
  53.         public void remove()      { throw new UnsupportedOperationException();  }
  54.         public Item next() {
  55.             if (!hasNext()) throw new NoSuchElementException();
  56.             return a[i++];
  57.         }
  58.     }
  59.     /**
  60.      * Unit tests the <tt>ResizingArrayBag</tt> data type.
  61.      */
  62.     public static void main(String[] args) {
  63.         ResizingArrayBag<String> bag = new ResizingArrayBag<String>();
  64.         bag.add("Hello");
  65.         bag.add("World");
  66.         bag.add("how");
  67.         bag.add("are");
  68.         bag.add("you");
  69.         for (String s : bag)
  70.             StdOut.println(s);
  71.     }
  72. }

可以用来统计数字来进行计算。

=============================================================================

队列:

全称先进先出队列,按照任务产生的顺序完成他们的策略,基本上每天都会用到:典型就是排队。服务优先等待最久的人。

主要的API:

           Queue()              创建一个空的队列
void         enqueue(Item item)         添加一个元素
Item              dequeue()                             删除最早添加的元素
boolean   isEmpty()            判断是否为空
int        size()              队列中的数量 
java代码实现:
链表:

  1. import java.util.Iterator;
  2. import java.util.NoSuchElementException;
  3. public class LinkedQueue<Item> implements Iterable<Item> {
  4.      private int N; // 队列元素的数量
  5.      private Node first; // 第一个进去的元素
  6.      private Node last; // 最后一个进去的元素
  7.      // 链表类
  8.      private class Node {
  9.           private Item item;
  10.           private Node next;
  11.      }
  12.      /**
  13.       * 创建一个空的链表
  14.       */
  15.      public LinkedQueue() {
  16.           first = null;
  17.           last = null;
  18.           N = 0;
  19.           assert check();
  20.      }
  21.      /**
  22.       * 判断链表是否为空
  23.       * 
  24.       * @return true if this queue is empty; false otherwise
  25.       */
  26.      public boolean isEmpty() {
  27.           return first == null;
  28.      }
  29.      /**
  30.       * 返回链表的数量
  31.       * 
  32.       * @return the number of items in this queue
  33.       */
  34.      public int size() {
  35.           return N;
  36.      }
  37.      /**
  38.       * 返回最近添加的元素
  39.       * 
  40.       * @return the item least recently added to this queue
  41.       * @throws java.util.NoSuchElementException
  42.       *             if this queue is empty
  43.       */
  44.      public Item peek() {
  45.           if (isEmpty())
  46.                throw new NoSuchElementException("Queue underflow");
  47.           return first.item;
  48.      }
  49.      /**
  50.       * 添加一个元素到队列中
  51.       * 
  52.       * @param item
  53.       *            the item to add
  54.       */
  55.      public void enqueue(Item item) {
  56.           Node oldlast = last;
  57.           last = new Node();
  58.           last.item = item;
  59.           last.next = null;
  60.           if (isEmpty())
  61.                first = last;
  62.           else
  63.                oldlast.next = last;
  64.           N++;
  65.           assert check();
  66.      }
  67.      /**
  68.       * 删除队列的第一个元素
  69.       * 
  70.       * @return the item on this queue that was least recently added
  71.       * @throws java.util.NoSuchElementException
  72.       *             if this queue is empty
  73.       */
  74.      public Item dequeue() {
  75.           if (isEmpty())
  76.                throw new NoSuchElementException("Queue underflow");
  77.           Item item = first.item;
  78.           first = first.next;
  79.           N--;
  80.           if (isEmpty())
  81.                last = null; // to avoid loitering
  82.           assert check();
  83.           return item;
  84.      }
  85.      /**
  86.       * 返回一个字符串这个队列的全部元素组成的
  87.       * 
  88.       * @return the sequence of items in FIFO order, separated by spaces
  89.       */
  90.      public String toString() {
  91.           StringBuilder s = new StringBuilder();
  92.           for (Item item : this)
  93.                s.append(item + " ");
  94.           return s.toString();
  95.      }
  96.      // check internal invariants
  97.      private boolean check() {
  98.           if (N == 0) {
  99.                if (first != null)
  100.                     return false;
  101.                if (last != null)
  102.                     return false;
  103.           } else if (N == 1) {
  104.                if (first == null || last == null)
  105.                     return false;
  106.                if (first != last)
  107.                     return false;
  108.                if (first.next != null)
  109.                     return false;
  110.           } else {
  111.                if (first == last)
  112.                     return false;
  113.                if (first.next == null)
  114.                     return false;
  115.                if (last.next != null)
  116.                     return false;
  117.                // check internal consistency of instance variable N
  118.                int numberOfNodes = 0;
  119.                for (Node x = first; x != null; x = x.next) {
  120.                     numberOfNodes++;
  121.                }
  122.                if (numberOfNodes != N)
  123.                     return false;
  124.                // check internal consistency of instance variable last
  125.                Node lastNode = first;
  126.                while (lastNode.next != null) {
  127.                     lastNode = lastNode.next;
  128.                }
  129.                if (last != lastNode)
  130.                     return false;
  131.           }
  132.           return true;
  133.      }
  134.      /**
  135.       * Returns an iterator that iterates over the items in this queue in FIFO
  136.       * order.
  137.       * 
  138.       * @return an iterator that iterates over the items in this queue in FIFO
  139.       *         order
  140.       */
  141.      public Iterator<Item> iterator() {
  142.           return new ListIterator();
  143.      }
  144.      // an iterator, doesn‘t implement remove() since it‘s optional
  145.      private class ListIterator implements Iterator<Item> {
  146.           private Node current = first;
  147.           public boolean hasNext() {
  148.                return current != null;
  149.           }
  150.           public void remove() {
  151.                throw new UnsupportedOperationException();
  152.           }
  153.           public Item next() {
  154.                if (!hasNext())
  155.                     throw new NoSuchElementException();
  156.                Item item = current.item;
  157.                current = current.next;
  158.                return item;
  159.           }
  160.      }
  161. }
数组:
 

  1. import java.util.Iterator;
  2. import java.util.NoSuchElementException;
  3. public class ResizingArrayQueue <Item> implements Iterable<Item>{
  4.      private Item[] q; // queue elements
  5.      private int N = 0; // number of elements on queue
  6.      private int first = 0; // index of first element of queue
  7.      private int last = 0; // index of next available slot
  8.      /**
  9.       * Initializes an empty queue.
  10.       */
  11.      public ResizingArrayQueue() {
  12.           // cast needed since no generic array creation in Java
  13.           q = (Item[]) new Object[2];
  14.      }
  15.      /**
  16.       * Is this queue empty?
  17.       * 
  18.       * @return true if this queue is empty; false otherwise
  19.       */
  20.      public boolean isEmpty() {
  21.           return N == 0;
  22.      }
  23.      /**
  24.       * Returns the number of items in this queue.
  25.       * 
  26.       * @return the number of items in this queue
  27.       */
  28.      public int size() {
  29.           return N;
  30.      }
  31.      // resize the underlying array
  32.      private void resize(int max) {
  33.           assert max >= N;
  34.           Item[] temp = (Item[]) new Object[max];
  35.           for (int i = 0; i < N; i++) {
  36.                temp[i] = q[(first + i) % q.length];
  37.           }
  38.           q = temp;
  39.           first = 0;
  40.           last = N;
  41.      }
  42.      /**
  43.       * Adds the item to this queue.
  44.       * 
  45.       * @param item
  46.       *            the item to add
  47.       */
  48.      public void enqueue(Item item) {
  49.           // double size of array if necessary and recopy to front of array
  50.           if (N == q.length)
  51.                resize(2 * q.length); // double size of array if necessary
  52.           q[last++] = item; // add item
  53.           if (last == q.length)
  54.                last = 0; // wrap-around
  55.           N++;
  56.      }
  57.      /**
  58.       * Removes and returns the item on this queue that was least recently added.
  59.       * 
  60.       * @return the item on this queue that was least recently added
  61.       * @throws java.util.NoSuchElementException
  62.       *             if this queue is empty
  63.       */
  64.      public Item dequeue() {
  65.           if (isEmpty())
  66.                throw new NoSuchElementException("Queue underflow");
  67.           Item item = q[first];
  68.           q[first] = null; // to avoid loitering
  69.           N--;
  70.           first++;
  71.           if (first == q.length)
  72.                first = 0; // wrap-around
  73.           // shrink size of array if necessary
  74.           if (N > 0 && N == q.length / 4)
  75.                resize(q.length / 2);
  76.           return item;
  77.      }
  78.      /**
  79.       * Returns the item least recently added to this queue.
  80.       * 
  81.       * @return the item least recently added to this queue
  82.       * @throws java.util.NoSuchElementException
  83.       *             if this queue is empty
  84.       */
  85.      public Item peek() {
  86.           if (isEmpty())
  87.                throw new NoSuchElementException("Queue underflow");
  88.           return q[first];
  89.      }
  90.      /**
  91.       * Returns an iterator that iterates over the items in this queue in FIFO
  92.       * order.
  93.       * 
  94.       * @return an iterator that iterates over the items in this queue in FIFO
  95.       *         order
  96.       */
  97.      public Iterator<Item> iterator() {
  98.           return new ArrayIterator();
  99.      }
  100.      // an iterator, doesn‘t implement remove() since it‘s optional
  101.      private class ArrayIterator implements Iterator<Item> {
  102.           private int i = 0;
  103.           public boolean hasNext() {
  104.                return i < N;
  105.           }
  106.           public void remove() {
  107.                throw new UnsupportedOperationException();
  108.           }
  109.           public Item next() {
  110.                if (!hasNext())
  111.                     throw new NoSuchElementException();
  112.                Item item = q[(i + first) % q.length];
  113.                i++;
  114.                return item;
  115.           }
  116.      }
  117.      
  118.      public static void main(String[] args) {
  119.           ResizingArrayQueue<String>s=new ResizingArrayQueue<String>();
  120.           s.enqueue("ppppp");
  121.           s.enqueue("eeee");
  122.           System.out.println(s.dequeue());
  123.      }
  124. }
 
栈:
下压栈 ,后进先出,好比浏览网页,的后退键等。
java实现:
链表:
  1. import java.util.Iterator;
  2. import java.util.NoSuchElementException;
  3. import java.util.Stack;
  4. public class LinkedStack<Item> implements Iterable<Item> {
  5.      private int N;
  6.      private Node first;
  7.      private class Node {
  8.           private Item item;
  9.           private Node next;
  10.      }
  11.      public LinkedStack() {
  12.           first = null;
  13.           N = 0;
  14.           assert check();
  15.      }
  16.      public boolean isEmpty() {
  17.           return first == null;
  18.      }
  19.      public int size() {
  20.           return N;
  21.      }
  22.      public void push(Item item) {
  23.           Node oldfirst = first;
  24.           first = new Node();
  25.           first.next = oldfirst;
  26.           first.item = item;
  27.           N++;
  28.           assert check();
  29.      }
  30.      public Item pop() {
  31.           if (isEmpty()) {
  32.                throw new NoSuchElementException("Stack underflow");
  33.           }
  34.           Item item = first.item;
  35.           first = first.next;
  36.           N--;
  37.           assert check();
  38.           return item;
  39.      }
  40.      public Item peak() {
  41.           if (isEmpty())
  42.                throw new NoSuchElementException("Queue underflow");
  43.           return first.item;
  44.      }
  45.      public String toString() {
  46.           StringBuilder s = new StringBuilder();
  47. //          for (Item item : this)
  48. //               s.append(item + " ");
  49.           for (Node x =first; x!=null; x=x.next) {
  50.                s.append(x.item + " ");
  51.           }
  52.           return s.toString();
  53.      }
  54.      private boolean check() {
  55.           if (N==0) {
  56.                if (first==null) {
  57.                     return false;
  58.                }else if (N==1) {
  59.                     if (first==null) {
  60.                          return false;
  61.                     }
  62.                     if (first.next!=null) {
  63.                          return false;
  64.                     }
  65.                }else {
  66.                     if (first.next==null) {
  67.                          return false;
  68.                     }
  69.                }
  70.           }
  71.           int numberOfNodes = 0;
  72.         for (Node x = first; x != null; x = x.next) {
  73.             numberOfNodes++;
  74.         }
  75.         if (numberOfNodes != N) return false;
  76.         return true;
  77.      }
  78.      @Override
  79.      public Iterator<Item> iterator() {
  80.           // TODO Auto-generated method stub
  81.           return new ListIterator();
  82.      }
  83.      private class ListIterator implements Iterator<Item> {
  84.           private Node current = first;
  85.           public boolean hasNext() {
  86.                return current != null;
  87.           }
  88.           public void remove() {
  89.                throw new UnsupportedOperationException();
  90.           }
  91.           public Item next() {
  92.                if (!hasNext())
  93.                     throw new NoSuchElementException();
  94.                Item item = current.item;
  95.                current = current.next;
  96.                return item;
  97.           }
  98.      }
  99.      
  100.      public static void main(String[] args) {
  101.           LinkedStack<String>s=new LinkedStack<String>();
  102.           Stack<Character>a=new Stack<Character>();
  103.           a.peek();
  104.      }
  105. }
数组实现:
    1. import java.util.Iterator;
    2. import java.util.NoSuchElementException;
    3. public class ResizingArrayStack<Item> implements Iterable<Item> {
    4.      private Item[] a;
    5.      private int N;
    6.      public ResizingArrayStack() {
    7.           a = (Item[]) new Object[2];
    8.      }
    9.      public boolean isEmpty() {
    10.           return N == 0;
    11.      }
    12.      public int size() {
    13.           return N;
    14.      }
    15.      private void resize(int cap) {
    16.           assert cap >= N;
    17.           Item[] temp = (Item[]) new Object[cap];
    18.           for (int i = 0; i < N; i++) {
    19.                temp[i] = a[i];
    20.           }
    21.           a = temp;
    22.      }
    23.      public void push(Item item) {
    24.           if (N == a.length) {
    25.                resize(2 * a.length);
    26.           }
    27.           a[N++] = item;
    28.      }
    29.      public Item pop() {
    30.           if (isEmpty()) {
    31.                throw new NoSuchElementException("Stack underflow");
    32.           }
    33.           Item item = a[N - 1];
    34.           a[N - 1] = null;
    35.           N--;
    36.           if (N > 0 && N == a.length / 4) {
    37.                resize(a.length / 2);
    38.           }
    39.           return item;
    40.      }
    41.      public Item peek() {
    42.           if (isEmpty())
    43.                throw new NoSuchElementException("Stack underflow");
    44.           return a[N - 1];
    45.      }
    46.      @Override
    47.      public Iterator<Item> iterator() {
    48.           return new ReverseArrayIterator();
    49.      }
    50.      private class ReverseArrayIterator implements Iterator<Item> {
    51.           private int i;
    52.           public ReverseArrayIterator() {
    53.                i = N - 1;
    54.           }
    55.           public boolean hasNext() {
    56.                return i >= 0;
    57.           }
    58.           public void remove() {
    59.                throw new UnsupportedOperationException();
    60.           }
    61.           public Item next() {
    62.                if (!hasNext())
    63.                     throw new NoSuchElementException();
    64.                return a[i--];
    65.           }
    66.      }
    67.      public static void main(String[] args) {
    68.           ResizingArrayStack<String> s = new ResizingArrayStack<String>();
    69.           s.push("kk");
    70.           s.push("pp");
    71.           s.push("pp");
    72.           s.push("pp");
    73.           System.out.println(s.pop());
    74.           System.out.println(s.pop());
    75.           System.out.println(s.pop());
    76.           System.out.println(s.pop());
    77.           System.out.println(s.N);
    78.      }
    79. }

algorithms第四版学习进程(一)背包,栈,队列

标签:

原文地址:http://www.cnblogs.com/wuwulalala/p/4593317.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!