gpt4 book ai didi

java - Java中向循环双向链表添加节点

转载 作者:行者123 更新时间:2023-12-02 03:19:13 25 4
gpt4 key购买 nike

我尝试创建并打印一个循环双向链表,其中包含保存字母表中每个字母值的节点。

这是迄今为止我的代码:

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);
}

关于java - Java中向循环双向链表添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39842954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com