如何在我的java代码中填充getItemSize()方法

时间:2014-02-22 01:11:04

标签: java

我有一个带有成员名称项的DListNode类。

/* DListNode.java */

/**
 * DListNode is a node in DList(Doubly linked list). 
 * @author mohet01
 *
 */
public class DListNode {

    /**
     * item references the item stored in the current node.
     * prev references the previous node in the DList.
     * next references the next node in the DList.
     */

    Object item;
    DListNode prev;
    DListNode next;

    /**
     * DListNode constructor with zero args
     */
    public DListNode(){
        this.item=null;
        this.prev=null;
        this.next=null;
    }

    /**
     * DListNode constructor with one arg
     */
    public DListNode(Object obj){
        this.item = obj;
        this.prev = null;
        this.next = null;
    }


    /**
     * getItem() returns the size of the queried item
     * @return
     */

    public Object getItemSize() {
         //solution required    
         return item;
    }
}

如果DListNode成员项指向TypeAndSize类的对象,

public class TypeAndSize {

    public int type;            //Ocean.EMPTY, Ocean.UNVISITEDSHARK, or Ocean.FISH
    public int size;                        // Number of cells in the run



    /**
     * Constructor for a TypeAndSize of specified species and run length.
     * @param species is Ocean.EMPTY, Ocean.SHARK, or Ocean.FISH.
     * @param runLength is the number of identical cells in this run.
     * @return the newly constructed Critter.
     * 
     */

    public TypeAndSize(int species, int runLength){

        if((species != Ocean.EMPTY) && (species != Ocean.SHARK) && (species != Ocean.FISH)){
            System.out.println("TypeAndSize Error: Illegal species.");
            System.exit(1);
        }

        if(runLength < 1){
            System.out.println("TypeAndSize Error: runLength must be atleast 1.");
            System.exit(1);
        }

        this.type = species;
        this.size = runLength;
    }


    public int getSize(){
        return size;
    }

}

我的目标是通过在DListNode类的getItemSize()方法中编写代码来引入成员大小。 以上两类是教授给出的骨架。 http://www.cs.berkeley.edu/~jrs/61bf06/hw/pj1/

我在TypeAndSize类中创建了getSize()方法。

请帮帮我!!!

... FYI 这是我第一次使用这种场景,就像我在2006年秋季伯克利课程网络广播中学习Java一样。这是Project1

中任务的一部分

请帮帮我!!!

1 个答案:

答案 0 :(得分:0)

假设您只在列表的第一个元素上调用此方法,这可以解决您的问题:

public int getItemSize() {
    int size = 0;
    DListNode node = this;
    while (node != null) {
        size++;
        node = node.next;
    }
    return size;
}

如果您希望从任何节点调用此方法,请使用此其他解决方案

 public Object getItemSize() {
    int size = 0;
    DListNode node = this;
    while (node != null) {
        size++;
        node = node.next;
    }
    node = prev;
    while (node != null) {
        size++;
        node = node.prev;
    }
    return size;
}