2

我必须创建一种方法来消除循环链表中的数字,比如我们的值最多为 9

1 2 3 4 5 6 7 8 9

并且我们希望不断地删除每第四个整数,它会如下所示

5 6 7 8 9 1 2 3; //  4 is removed
9 1 2 3 5 6 7;   //  8 is removed
5 6 7 9 1 2;     //  3 is removed
1 2 5 6 7;       //  9 is removed
7 1 2 5;         //  6 is removed
7 1 2;           // 5 is removed
1 2;             // 7 is removed
1;               // 2 is removed

我必须创建一个移动来遍历元素,并创建一个消除来删除元素,但我可以自己做到这一点。我的 toString(); 有问题 方法,我目前没有返回任何值。

class Digit{ 

    class DigitNode
    {
            public int num=0;           // Digit's position in line
            public DigitNode next=null; // Reference to next digit
            /**
            * Digit constructor, initializes number
            */
            public DigitNode(int number)
            {
                   //
                num = number;
                next = null;
            }
    }

    private int number;
    private DightNode current = null;   // Linked list of digits
    private DigitNode tail = null;  // Tracks end of list as it is constructed

    /**
     * constructs a circular linked list of
     * @param n DigitNodes, current is the first DigitNode and tail is the last DigitNode(next of tail is current)
     */

    public Digit(int n)
    {
        //
        number = n;
        current = null;
        tail = null;
     }

     /*
     * prints all Digits starting from current until tail
     */
     @Override
     public String toString()
     {
    //
         String strVal = "";
         DigitNode position = current;
         while (position != null) {
             strVal = strVal + position + " ";
             position = current.next;
         }
         return strVal;
     }

对我来说,我知道我将 position 指定为当前值,应该是1,因此虽然 position 不是null,但strVal应该是 position [1]+" "的间距。然后我将 position 称为下一个值[2],并且我继续直到null它之后9。因此strVal应该是1 2 3 4 5 6 7 8 9。但不幸的是,我没有返回任何东西,我尝试调试,并放置一些System.out.prinln();标记以查看我是否返回任何东西,但我没有。

4

2 回答 2

1

首先,您需要DigitDigitNode's 对象填充您的对象。我没有从您发布的快照中看到执行此操作的代码。
大概您可以在构造函数中执行此操作Digit,或创建方法Digit.add( DigitNodenode)。你需要这个,否则你current将永远为空。


接下来,您需要添加 toString in,DigitNode正如我之前在评论中所说,或者您可以将Digit.toString() 更改为:

strVal = strVal + position.num + " "; // note position.num to get the number
于 2013-11-20T08:43:53.083 回答
0

你在 DigitNode 中没有 toString() 所以当你打电话时

strVal = strVal + position + " ";

您只是将默认的 toString() 方法用于位置(即 DigitNode)附加到 strVal。这是因为使用 '+' 将对象添加到 String 调用它的 toString() 来获取要添加到 String 的内容(在本例中为 strVal)。

于 2013-11-20T08:37:34.450 回答