算法第四版1.3背包、队列和栈:习题1.3.50

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class Stack  implements Iterable{
    public static void main(String[]args){
        Stack stack=new Stack<>();
        for (int i=0;i<10;i++)
            stack.push(i);
        for (int i:stack){
            StdOut.print(i+" ");
            if (i==5)//modify stack while iterating
                stack.push(10);
        }
    }

    private Node first; //top of stack (most recently added node)
    private int N;      //number of items

    private class Node{
        //nested class to define nodes
        Item item;
        Node next;
    }
    public Stack(){
        first=null;
        N=0;
    }
    public Stack(Stack s){//1.3.42
        Stack temp=new Stack<>();
        int N=s.size();
        for (int i=0;i Stack copy(Stack s){
        Stack result=new Stack<>();
        Stack temp=new Stack<>();
        Iterator iterator=s.iterator();
        while (iterator.hasNext())
            temp.push(iterator.next());
        iterator=temp.iterator();
        while (iterator.hasNext())
            result.push(iterator.next());
        return result;
    }
    public Iterator iterator(){
        return new StackIterator();
    }
    private class StackIterator implements Iterator{
        private Node current=first;
        private int count=size();
        public boolean hasNext(){
            if (count!=size())
                throw new ConcurrentModificationException("Stack was being modified!");
            return current!=null;
        }
        public void remove(){}
        public Item next(){
            if (count!=size())
                throw new ConcurrentModificationException("Stack was being modified!");
            Item item=current.item;
            current=current.next;
            return item;
        }
    }
}

 

你可能感兴趣的:(算法第四版1.3背包,队列和栈课后习题)