我尝试创建并打印一个循环双链表,它将包含保存字母表中每个字母值的节点。
下面是我的代码: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);
}
问题:我已经尝试打印列表,但似乎没有任何显示,他们在控制台中没有错误消息。任何帮助都会很感激。
因为列表是循环的,所以代码:
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);
}