簡體   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