算法Sedgewick第四版-第1章基础-011一用链表实现bag、queue、stack

1.

  1 package algorithms.ADT;
  2 
  3 /******************************************************************************
  4  *  Compilation:  javac Bag.java
  5  *  Execution:    java Bag < input.txt
  6  *  Dependencies: StdIn.java StdOut.java
  7  *
  8  *  A generic bag or multiset, implemented using a singly-linked list.
  9  *
 10  *  % more tobe.txt 
 11  *  to be or not to - be - - that - - - is
 12  *
 13  *  % java Bag < tobe.txt
 14  *  size of bag = 14
 15  *  is
 16  *  -
 17  *  -
 18  *  -
 19  *  that
 20  *  -
 21  *  -
 22  *  be
 23  *  -
 24  *  to
 25  *  not
 26  *  or
 27  *  be
 28  *  to
 29  *
 30  ******************************************************************************/
 31 
 32 import java.util.Iterator;
 33 import java.util.NoSuchElementException;
 34 
 35 import algorithms.util.StdIn;
 36 import algorithms.util.StdOut;
 37 
 38 /**
 39  *  The <tt>Bag</tt> class represents a bag (or multiset) of 
 40  *  generic items. It supports insertion and iterating over the 
 41  *  items in arbitrary order.
 42  *  <p>
 43  *  This implementation uses a singly-linked list with a static nested class Node.
 44  *  See {@link LinkedBag} for the version from the
 45  *  textbook that uses a non-static nested class.
 46  *  The <em>add</em>, <em>isEmpty</em>, and <em>size</em> operations
 47  *  take constant time. Iteration takes time proportional to the number of items.
 48  *  <p>
 49  *  For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
 50  *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 51  *
 52  *  @author Robert Sedgewick
 53  *  @author Kevin Wayne
 54  *
 55  *  @param <Item> the generic type of an item in this bag
 56  */
 57 public class Bag<Item> implements Iterable<Item> {
 58     private Node<Item> first;    // beginning of bag
 59     private int N;               // number of elements in bag
 60 
 61     // helper linked list class
 62     private static class Node<Item> {
 63         private Item item;
 64         private Node<Item> next;
 65     }
 66 
 67     /**
 68      * Initializes an empty bag.
 69      */
 70     public Bag() {
 71         first = null;
 72         N = 0;
 73     }
 74 
 75     /**
 76      * Returns true if this bag is empty.
 77      *
 78      * @return <tt>true</tt> if this bag is empty;
 79      *         <tt>false</tt> otherwise
 80      */
 81     public boolean isEmpty() {
 82         return first == null;
 83     }
 84 
 85     /**
 86      * Returns the number of items in this bag.
 87      *
 88      * @return the number of items in this bag
 89      */
 90     public int size() {
 91         return N;
 92     }
 93 
 94     /**
 95      * Adds the item to this bag.
 96      *
 97      * @param  item the item to add to this bag
 98      */
 99     public void add(Item item) {
100         Node<Item> oldfirst = first;
101         first = new Node<Item>();
102         first.item = item;
103         first.next = oldfirst;
104         N++;
105     }
106 
107 
108     /**
109      * Returns an iterator that iterates over the items in this bag in arbitrary order.
110      *
111      * @return an iterator that iterates over the items in this bag in arbitrary order
112      */
113     public Iterator<Item> iterator()  {
114         return new ListIterator<Item>(first);  
115     }
116 
117     // an iterator, doesn't implement remove() since it's optional
118     private class ListIterator<Item> implements Iterator<Item> {
119         private Node<Item> current;
120 
121         public ListIterator(Node<Item> first) {
122             current = first;
123         }
124 
125         public boolean hasNext()  { return current != null;                     }
126         public void remove()      { throw new UnsupportedOperationException();  }
127 
128         public Item next() {
129             if (!hasNext()) throw new NoSuchElementException();
130             Item item = current.item;
131             current = current.next; 
132             return item;
133         }
134     }
135 
136     /**
137      * Unit tests the <tt>Bag</tt> data type.
138      */
139     public static void main(String[] args) {
140         Bag<String> bag = new Bag<String>();
141         while (!StdIn.isEmpty()) {
142             String item = StdIn.readString();
143             bag.add(item);
144         }
145 
146         StdOut.println("size of bag = " + bag.size());
147         for (String s : bag) {
148             StdOut.println(s);
149         }
150     }
151 
152 
153 }

 

2.

  1 package algorithms.ADT;
  2 
  3 /******************************************************************************
  4  *  Compilation:  javac Queue.java
  5  *  Execution:    java Queue < input.txt
  6  *  Dependencies: StdIn.java StdOut.java
  7  *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt  
  8  *
  9  *  A generic queue, implemented using a linked list.
 10  *
 11  *  % java Queue < tobe.txt 
 12  *  to be or not to be (2 left on queue)
 13  *
 14  ******************************************************************************/
 15 
 16 import java.util.Iterator;
 17 import java.util.NoSuchElementException;
 18 
 19 import algorithms.util.StdIn;
 20 import algorithms.util.StdOut;
 21 
 22 /**
 23  *  The <tt>Queue</tt> class represents a first-in-first-out (FIFO)
 24  *  queue of generic items.
 25  *  It supports the usual <em>enqueue</em> and <em>dequeue</em>
 26  *  operations, along with methods for peeking at the first item,
 27  *  testing if the queue is empty, and iterating through
 28  *  the items in FIFO order.
 29  *  <p>
 30  *  This implementation uses a singly-linked list with a static nested class for
 31  *  linked-list nodes. See {@link LinkedQueue} for the version from the
 32  *  textbook that uses a non-static nested class.
 33  *  The <em>enqueue</em>, <em>dequeue</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
 34  *  operations all take constant time in the worst case.
 35  *  <p>
 36  *  For additional documentation, see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
 37  *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 38  *
 39  *  @author Robert Sedgewick
 40  *  @author Kevin Wayne
 41  *
 42  *  @param <Item> the generic type of an item in this queue
 43  */
 44 public class Queue<Item> implements Iterable<Item> {
 45     private Node<Item> first;    // beginning of queue
 46     private Node<Item> last;     // end of queue
 47     private int N;               // number of elements on queue
 48 
 49     // helper linked list class
 50     private static class Node<Item> {
 51         private Item item;
 52         private Node<Item> next;
 53     }
 54 
 55     /**
 56      * Initializes an empty queue.
 57      */
 58     public Queue() {
 59         first = null;
 60         last  = null;
 61         N = 0;
 62     }
 63 
 64     /**
 65      * Returns true if this queue is empty.
 66      *
 67      * @return <tt>true</tt> if this queue is empty; <tt>false</tt> otherwise
 68      */
 69     public boolean isEmpty() {
 70         return first == null;
 71     }
 72 
 73     /**
 74      * Returns the number of items in this queue.
 75      *
 76      * @return the number of items in this queue
 77      */
 78     public int size() {
 79         return N;     
 80     }
 81 
 82     /**
 83      * Returns the item least recently added to this queue.
 84      *
 85      * @return the item least recently added to this queue
 86      * @throws NoSuchElementException if this queue is empty
 87      */
 88     public Item peek() {
 89         if (isEmpty()) throw new NoSuchElementException("Queue underflow");
 90         return first.item;
 91     }
 92 
 93     /**
 94      * Adds the item to this queue.
 95      *
 96      * @param  item the item to add
 97      */
 98     public void enqueue(Item item) {
 99         Node<Item> oldlast = last;
100         last = new Node<Item>();
101         last.item = item;
102         last.next = null;
103         if (isEmpty()) first = last;
104         else           oldlast.next = last;
105         N++;
106     }
107 
108     /**
109      * Removes and returns the item on this queue that was least recently added.
110      *
111      * @return the item on this queue that was least recently added
112      * @throws NoSuchElementException if this queue is empty
113      */
114     public Item dequeue() {
115         if (isEmpty()) throw new NoSuchElementException("Queue underflow");
116         Item item = first.item;
117         first = first.next;
118         N--;
119         if (isEmpty()) last = null;   // to avoid loitering
120         return item;
121     }
122 
123     /**
124      * Returns a string representation of this queue.
125      *
126      * @return the sequence of items in FIFO order, separated by spaces
127      */
128     public String toString() {
129         StringBuilder s = new StringBuilder();
130         for (Item item : this)
131             s.append(item + " ");
132         return s.toString();
133     } 
134 
135     /**
136      * Returns an iterator that iterates over the items in this queue in FIFO order.
137      *
138      * @return an iterator that iterates over the items in this queue in FIFO order
139      */
140     public Iterator<Item> iterator()  {
141         return new ListIterator<Item>(first);  
142     }
143 
144     // an iterator, doesn't implement remove() since it's optional
145     private class ListIterator<Item> implements Iterator<Item> {
146         private Node<Item> current;
147 
148         public ListIterator(Node<Item> first) {
149             current = first;
150         }
151 
152         public boolean hasNext()  { return current != null;                     }
153         public void remove()      { throw new UnsupportedOperationException();  }
154 
155         public Item next() {
156             if (!hasNext()) throw new NoSuchElementException();
157             Item item = current.item;
158             current = current.next; 
159             return item;
160         }
161     }
162 
163 
164     /**
165      * Unit tests the <tt>Queue</tt> data type.
166      */
167     public static void main(String[] args) {
168         Queue<String> q = new Queue<String>();
169         while (!StdIn.isEmpty()) {
170             String item = StdIn.readString();
171             if (!item.equals("-")) q.enqueue(item);
172             else if (!q.isEmpty()) StdOut.print(q.dequeue() + " ");
173         }
174         StdOut.println("(" + q.size() + " left on queue)");
175     }
176 }

 

3.

  1 package algorithms.ADT;
  2 
  3 /******************************************************************************
  4  *  Compilation:  javac Stack.java
  5  *  Execution:    java Stack < input.txt
  6  *  Dependencies: StdIn.java StdOut.java
  7  *
  8  *  A generic stack, implemented using a singly-linked list.
  9  *  Each stack element is of type Item.
 10  *
 11  *  This version uses a static nested class Node (to save 8 bytes per
 12  *  Node), whereas the version in the textbook uses a non-static nested
 13  *  class (for simplicity).
 14  *  
 15  *  % more tobe.txt 
 16  *  to be or not to - be - - that - - - is
 17  *
 18  *  % java Stack < tobe.txt
 19  *  to be not that or be (2 left on stack)
 20  *
 21  ******************************************************************************/
 22 
 23 import java.util.Iterator;
 24 import java.util.NoSuchElementException;
 25 
 26 import algorithms.util.StdIn;
 27 import algorithms.util.StdOut;
 28 
 29 
 30 /**
 31  *  The <tt>Stack</tt> class represents a last-in-first-out (LIFO) stack of generic items.
 32  *  It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
 33  *  for peeking at the top item, testing if the stack is empty, and iterating through
 34  *  the items in LIFO order.
 35  *  <p>
 36  *  This implementation uses a singly-linked list with a static nested class for
 37  *  linked-list nodes. See {@link LinkedStack} for the version from the
 38  *  textbook that uses a non-static nested class.
 39  *  The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>
 40  *  operations all take constant time in the worst case.
 41  *  <p>
 42  *  For additional documentation,
 43  *  see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
 44  *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 45  *
 46  *  @author Robert Sedgewick
 47  *  @author Kevin Wayne
 48  *
 49  *  @param <Item> the generic type of an item in this stack
 50  */
 51 public class Stack<Item> implements Iterable<Item> {
 52     private Node<Item> first;     // top of stack
 53     private int N;                // size of the stack
 54 
 55     // helper linked list class
 56     private static class Node<Item> {
 57         private Item item;
 58         private Node<Item> next;
 59     }
 60 
 61     /**
 62      * Initializes an empty stack.
 63      */
 64     public Stack() {
 65         first = null;
 66         N = 0;
 67     }
 68 
 69     /**
 70      * Returns true if this stack is empty.
 71      *
 72      * @return true if this stack is empty; false otherwise
 73      */
 74     public boolean isEmpty() {
 75         return first == null;
 76     }
 77 
 78     /**
 79      * Returns the number of items in this stack.
 80      *
 81      * @return the number of items in this stack
 82      */
 83     public int size() {
 84         return N;
 85     }
 86 
 87     /**
 88      * Adds the item to this stack.
 89      *
 90      * @param  item the item to add
 91      */
 92     public void push(Item item) {
 93         Node<Item> oldfirst = first;
 94         first = new Node<Item>();
 95         first.item = item;
 96         first.next = oldfirst;
 97         N++;
 98     }
 99 
100     /**
101      * Removes and returns the item most recently added to this stack.
102      *
103      * @return the item most recently added
104      * @throws NoSuchElementException if this stack is empty
105      */
106     public Item pop() {
107         if (isEmpty()) throw new NoSuchElementException("Stack underflow");
108         Item item = first.item;        // save item to return
109         first = first.next;            // delete first node
110         N--;
111         return item;                   // return the saved item
112     }
113 
114 
115     /**
116      * Returns (but does not remove) the item most recently added to this stack.
117      *
118      * @return the item most recently added to this stack
119      * @throws NoSuchElementException if this stack is empty
120      */
121     public Item peek() {
122         if (isEmpty()) throw new NoSuchElementException("Stack underflow");
123         return first.item;
124     }
125 
126     /**
127      * Returns a string representation of this stack.
128      *
129      * @return the sequence of items in this stack in LIFO order, separated by spaces
130      */
131     public String toString() {
132         StringBuilder s = new StringBuilder();
133         for (Item item : this)
134             s.append(item + " ");
135         return s.toString();
136     }
137        
138 
139     /**
140      * Returns an iterator to this stack that iterates through the items in LIFO order.
141      *
142      * @return an iterator to this stack that iterates through the items in LIFO order
143      */
144     public Iterator<Item> iterator() {
145         return new ListIterator<Item>(first);
146     }
147 
148     // an iterator, doesn't implement remove() since it's optional
149     private class ListIterator<Item> implements Iterator<Item> {
150         private Node<Item> current;
151 
152         public ListIterator(Node<Item> first) {
153             current = first;
154         }
155 
156         public boolean hasNext() {
157             return current != null;
158         }
159 
160         public void remove() {
161             throw new UnsupportedOperationException();
162         }
163 
164         public Item next() {
165             if (!hasNext()) throw new NoSuchElementException();
166             Item item = current.item;
167             current = current.next; 
168             return item;
169         }
170     }
171 
172 
173     /**
174      * Unit tests the <tt>Stack</tt> data type.
175      */
176     public static void main(String[] args) {
177         Stack<String> s = new Stack<String>();
178         while (!StdIn.isEmpty()) {
179             String item = StdIn.readString();
180             if (!item.equals("-")) s.push(item);
181             else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
182         }
183         StdOut.println("(" + s.size() + " left on stack)");
184     }
185 }

 

posted @ 2016-04-19 16:58  shamgod  阅读(478)  评论(0编辑  收藏  举报
haha