Circular Linked List
add メソッドを使用せずにシングルを作成することについて質問があります。Node の内部クラスと、toString
メソッドを持つ外部のコンストラクターです。
私は苦労していreturning
ますList
、私は継続的に何も返しません。addメソッドを実装できないため、理由がわかりません。コンストラクター内で循環リンク リストを作成する必要があるため、それについて少し理解を深めることができます。しかし、どのように値を自分Nodes
の ofhead
とに割り当てるのですか?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 が無限に参照されるため、 null になることはありません。ただし、少なくとも何も返さないのではなく、何かを返します。
私が電話
Number newNum = new Number(6);
System.out.println(newNum);
すると言う
1 2 3 4 5 6