我试图创建并打印一个圆形双向链接列表,其中包含保存字母表中每个字母值的节点。
到目前为止,这是我的代码:
CircularDoublyList.java
public static void main(String[] args)
{
CDLL<Character> head = null;
CDLL<Character> tail = null;
CDLL <Character> p = null;
for(char c = 'A'; c <= 'Z'; c++) {
p = new CDLL<Character>(c, null, null);
if (head == null)
{
p.setNext(p);
p.setPrevious(p);
head = p;
tail = head;
}
else
{
p.setPrevious(tail);
tail.setNext(p);
head.setPrevious(p);
p.setNext(head);
head = p;
}
}
print(p);
}
public static void print(CDLL<Character> list) {
String str = "";
while(list != null) {
str += list.getPrevious().getValue() + " ";
list = list.getPrevious();
}
System.out.print(str);
}
问题:我已尝试打印列表,但似乎没有任何内容显示,并且它们在控制台中没有错误消息。任何帮助,将不胜感激。
答案 0 :(得分:2)
好吧,因为列表是循环的,代码是:
while(list != null) {
str += list.getPrevious().getValue() + " ";
list = list.getPrevious();
}
将继续循环,永远不会停止。
只需将方法更改为在再次找到第一个节点时停止:
public static void print(CDLL<Character> list) {
String str = "";
CDLL<Character> first = null;
while (true) {
str += list.getPrevious().getValue() + " ";
if (first == null)
first = list.getPrevious();
else if (first == list.getPrevious())
break;
list = list.getPrevious();
}
System.out.print(str);
}