我有一个关于创建Circular Linked List
没有添加方法的单曲的问题。只是 Node 的一个内部类,然后是一个带有toString
方法的外部构造函数。
我很难returning
过List
,我一直没有回报。我不知道为什么,因为我无法实现 add 方法。我必须在我的构造函数中创建一个循环链接列表,以便让我对它有一些了解。但是我如何将值分配给我Nodes
的head
和tail
class Number{
class Node
{
public int num=0; // node's position in line
public Node next=null; // Reference to next node
/**
* Node constructor, initializes number
*/
public Node(int number)
{
//
num = number;
next = null;
}
public String toString() {
return "" + num;
}
}
private int number;
private Node head = null; // Linked list of prisoners
private Node tail = null; // Tracks end of list as it is constructed
/**
* constructs a circular linked list of
* @param n Nodes, current is the first Node and tail is the last Node (next of tail is current)
*/
public Number(int n)
{
//
number = n;
LinkedList numb1 = new LinkedList();
for (int i = 1; i <= number; i++) {
numb1.add(i) //head I will have 1, 2, 3... n
}
head = null; //how would I make this reference head?
tail = null; //how would I make this reference tail?
}
/*
* prints all Numbers starting from head until tail
*/
@Override
public String toString()
{
//
String strVal = "";
for (Node current = head; current != null; current = head.next) {
strVal = strVal + current.num;
}
return strVal;
}
我认为原因在于 for loop
。
通过拥有current != null
,它会继续运行,因为 current 永远不能为空,因为它无休止地引用,因为它是一个循环链接列表。但是,它至少会返回一些东西,而不是什么都没有。
说我打电话
Number newNum = new Number(6);
System.out.println(newNum);
我应该出局
1 2 3 4 5 6