我有一个关于在没有添加方法的情况下创建单个Circular Linked List
的问题。只是一个Node的内部类,然后是一个带有toString
方法的构造函数。
我很难returning
List
,我不断返回任何东西。我迷失了为什么因为我无法实现添加方法。我必须在我的构造函数中创建一个循环链接列表,这样我就能对它有所了解。但是,如何将值分配给Nodes
和head
的{{1}}
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;
}
。
通过拥有loop
,它会继续运行,因为当前它永远是无效的,因为它是一个循环的链表。但是,它至少会返回一些东西而不是什么。
说我打电话
current != null
Number newNum = new Number(6);
我应该把
System.out.println(newNum);
答案 0 :(得分:1)
使用此数据结构
class CList {
int size;
CNode head;
class CNode {
int data;
CNode next;
}
}
在CList初始化head
到null
和size
到0的构造函数中。
答案 1 :(得分:0)
public Number(int n) { number = n; head = new Node(0); Node prev = head; for (int i = 1; i <=number; i++) { Node node = new Node(i); prev.next=node; // head I will have 1, 2, 3... n prev=node; } tail=prev; }
2。在toString方法中,你总是引用head.next,它导致infiinte循环,因为你从未命中null(当前!= null将永远不会在你的代码中变为真)
public String toString() { String strVal = ""; for (Node current = head; current != null; current = current.next) { strVal = strVal +" "+ current.num; } return strVal; }
编辑:我想补充的一点是,你的实现是纯链表而不是循环链表。要使它成为循环,你应该指向尾部,tail=head