Java循环链表

时间:2013-11-20 08:21:47

标签: java list linked-list circular-list

我必须创建一个方法来消除循环链表中的数字 说我们的价值最高为9

1 2 3 4 5 6 7 8 9

我们希望不断删除每个经过的第4个整数,它将如下所示

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;
     }

对我来说,我理解我将位置指定为当前值1,因此当位置不是null时,strVal是位置{{1} } + [1]表示间距。然后我将位置称为下一个" "值,并继续[2]之后null。因此9应为strVal。但不幸的是,我没有回复任何东西,我尝试调试,并放置一些1 2 3 4 5 6 7 8 9标记,看看我是否还有任何东西,但我没有。

2 个答案:

答案 0 :(得分:1)

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


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

strVal = strVal + position.num + " "; // note position.num to get the number

答案 1 :(得分:0)

您在DigitNode中没有toString(),所以当您致电

strVal = strVal + position + " ";

你只是附加到strVal,无论默认的toString()方法是什么位置,这是一个DigitNode。这是因为将一个对象添加到带有'+'的String调用它的toString()来获取要添加到String的内容(在本例中为strVal)。

相关问题