zoukankan      html  css  js  c++  java
  • Algs4-1.3.12在可迭代Stack用例中写一个copy栈方法

     1.3.12编写一个可迭代的Stack用例,它含有一个静态的copy()方法,接受一个字符串的栈作为参数,并返回该栈的一个副本。注意:这种能是迭代器价值的一个重要体现,因为有了它我们无需改变基本API就能够实现这种功能。
    答:
    图片
    public class test
    {
       public static void main(String[] args)
       {
           Stack<String> s=new Stack<String>();
           while(!StdIn.isEmpty())
           {
               String item=StdIn.readString();
               s.push(item);
            }
            //
            StdOut.println("Stack of s before copy:");
               show(s);
            //
               Stack<String> s2=copy(s);
               StdOut.println("Stack of s after copy:");
               show(s);
               StdOut.println("Stack of s copy:");
               show(s2);
         
        }//end main
       public static Stack<String> copy(Stack<String> s)
       {
           Stack<String> tempStack=new Stack<String>();
           Stack<String> copyStack=new Stack<String>();
           for(String item:s)
               tempStack.push(item);
          
           for(String item:tempStack)
               copyStack.push(item);
           return copyStack;
          
       }
       private static void show(Stack<String> s)
       {
           for(String item:s)
               StdOut.print(item);
           StdOut.println();
       }
    }//end class

  • 相关阅读:
    [bzoj1568]李超线段树模板题(标志永久化)
    [tyvj1860]后缀数组
    [poj3264]rmq算法学习(ST表)
    LintCode-82.落单的数
    LintCode-53.翻转字符串
    LintCode-56.两数之和
    LintCode-379.将数组重新排序以构造最小值
    LintCode-5.第k大元素
    LintCode-3.统计数字
    LintCode-4.丑数 II
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9849408.html
Copyright © 2011-2022 走看看