繁体   English   中英

Java循环链表

[英]Java Circular Linked List

我必须创建一种方法来消除循环链表中的数字,说我们的值最大为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为位置[1] + " "用于间隔。 然后我将position称为下一个值[2] ,然后继续直到9之后的null 因此strVal应该是1 2 3 4 5 6 7 8 9 但不幸的是,我没有返回任何东西,我尝试调试并放置一些System.out.prinln(); 标记以查看我是否要退货,但我没有。

首先,您需要用DigitNode的对象填充Digit 我看不到从您发布的快照中执行此操作的代码。
大概可以在Digit构造函数中执行此操作,或创建Digit .add( DigitNode node)方法。 您需要这个,否则您的current将始终为null。


接下来,您需要像我之前在评论中所说的那样,在DigitNode添加toString,也可以将Digit .toString()更改为:

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

您在DigitNode中没有toString(),因此在调用时

strVal = strVal + position + " ";

您只需将strVal的默认toString()方法附加到strVal,这就是DigitNode。 这是因为将对象添加到带有'+'的字符串中会调用toString()来将某些内容添加到字符串中(在本例中为strVal)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM