我必须创建一个方法来消除循环链表中的数字
假设我们的值高达 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;
}
对我来说,我知道我正在将 position 指定为当前值,它应该是 1
,因此当 position 不是 null
时,strVal
为 [1]
+ ""
的位置。然后我将 position 称为下一个值,即 [2]
,并继续直到 null
,它在 9
之后。因此 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
关于Java循环链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20090700/