【发布时间】:2013-11-20 08:21:47
【问题描述】:
我必须创建一种方法来消除循环链表中的数字
假设我们的值最大为 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] + " " 的间距。然后我将位置称为下一个值,即[2],并继续直到null,即在9 之后。因此strVal 应该是1 2 3 4 5 6 7 8 9。但不幸的是,我没有返回任何东西,我尝试调试,并放置一些 System.out.prinln(); 标记以查看我是否返回任何东西,但我没有。
【问题讨论】:
-
你需要在你的 DigitNode 中有 toString 方法: public String toString { return "" + number; }
-
我已经这样做了,但仍然得到相同的输出。请问@kiruwka,在DigitNode内部类中实现toString()方法有什么作用?
-
请看我的回答。您是否真的在列表中添加了任何节点并在打印之前更新了
current? -
不,我没有,我知道我需要一个 add 方法来添加节点。但是我的导师通常会提供所有必要的方法,所以我第二次怀疑我对 addmethod 的判断。
标签: java list linked-list circular-list