我必须创建一种方法来消除循环链表中的数字,比如我们的值最多为 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();
标记以查看我是否返回任何东西,但我没有。