算法-第四版-练习1.3.1解答

为FixedCapacityStackOfStrings添加一个方法isFull()。

FixedCapacityStackOfStrings:

/**
 * Description : 
 * Author      : mn@furzoom.com
 * Date        : Sep 28, 2016 11:23:52 AM
 * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved.
 */
package com.furzoom.lab.algs.ch103;

/**
 * ClassName    : FixedCapacityStackOfStrings <br>
 * Function     : TODO ADD FUNCTION. <br>
 * date         : Sep 28, 2016 11:23:52 AM <br>
 * 
 * @version 
 */
public class FixedCapacityStackOfStrings
{
    private String[] a; // stack entries
    private int n;      // size;
    public FixedCapacityStackOfStrings(int cap)
    {
        a = new String[cap];
    }
    
    public boolean isEmpty() 
    {
        return n == 0;
    }
    
    public int size()
    {
        return n;
    }
    
    public void push(String item)
    {
        a[n++] = item;
    }
    
    public String pop()
    {
        return a[--n];
    }
    
    public boolean isFull()
    {
        return n == a.length;
    }
    
    public static void main(String[] args)
    {
        
    }

}

测试:

/**
 * Description : 
 * Author      : mn@furzoom.com
 * Date        : Sep 28, 2016 11:26:45 AM
 * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved.
 */
package com.furzoom.lab.algs.ch103;

import edu.princeton.cs.algs4.StdIn;

/**
 * ClassName    : E10301 <br>
 * Function     : TODO ADD FUNCTION. <br>
 * date         : Sep 28, 2016 11:26:45 AM <br>
 * 
 * @version 
 */
public class E10301
{
    public static void main(String[] args)
    {
        FixedCapacityStackOfStrings s;
        s = new FixedCapacityStackOfStrings(3);
        while (!StdIn.isEmpty())
        {
            String item = StdIn.readString();
            if (s.isFull())
            {
                System.out.println("Stack is full.");
                break;
            }
            s.push(item);
        }
    }

}

结果:

>java -cp ".;../lib/algs4.jar" com
.furzoom.lab.algs.ch103.E10301
to
be
or
not
Stack is full.

算法-第四版-1.3 背包、队列和栈-习题索引汇总

算法-第四版习题索引汇总

原文地址:https://www.cnblogs.com/furzoom/p/7710209.html