Имам въпрос относно създаването на единичен Circular Linked List
без метод за добавяне. Само вътрешен клас на Node и след това конструктор отвън с toString
метод.
Трудно ми е returning
List
, непрекъснато не връщам нищо. и не знам защо, защото не мога да внедря метод за добавяне. Трябва да създам кръгъл свързан списък в моя конструктор, така че това ми дава малко представа за него. Но как да присвоя стойностите на моите 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
Node$Node
? - person chrylis -cautiouslyoptimistic-   schedule 21.11.2013