java - 将数组转换为 LinkedList

标签 java singly-linked-list

我有一个字符数组,我试图将每个字符转换为链接到行中下一个节点的节点。问题是我一直陷入无限循环,我不知道为什么。这是我的代码:

String map = "ABBACBCCA";
char[] charArray = map.toCharArray();
ListNode head;
ListNode temp;
ListNode next;

for (int i = 0; i < charArray.length - 1; i++) {
     temp = new ListNode(charArray[i]);
     next = new ListNode(charArray[i+1]);
     temp.next = next;

     if (i == 0) {
          head = temp;
     }
}

ListNode 类如下所示:

class ListNode<T> {
     public T data = null;
     public ListNode next = null;

     public ListNode(T data) {
          this.data = data;
     }
}

看起来它到达了 for 循环的最后一次迭代,然后陷入了无限循环。有人知道为什么吗?

最佳答案

对于开始,我认为你会想要:

next = new ListNode(charArray[i]);

成为

next = new ListNode(charArray[i+1]);

我注意到的其他事情:

for (int i = 0; i < charArray.length - 1; i++) {
     temp = new ListNode(charArray[i]);
     next = new ListNode(charArray[i+1]);
     temp.next = next;

          if (i == 0) {
            head = temp;
           }
     }

我不认为这会产生你想要的结果。它不会给你 A->B->B->A 等等,更多的是它会给你 -> A->B,B->B 等等。不确定这是否是你想要的。

此外,我认为这应该会让你受益匪浅:

String map = "ABBACBCCA";
        ListNode<Character> head = null;
        ListNode<Character> newHead = null;
        ListNode<Character> next = null;

        char[] charArray = map.toCharArray();

        head = newHead = new ListNode<Character>(charArray[0]);
        for (int i = 1; i < charArray.length - 1; i++) {
            next = new ListNode<Character>(charArray[i]);

            newHead.next = next;

            newHead = next;
        }

基本上是创建和链接以及创建和链接。 (对我来说测试得很好)即将到来的丑陋!

System.out.println(head.data);
        ListNode<Character> nextptr = head.next;
        while (true) {

            if (nextptr.next == null) {
                break;
            }
            System.out.println(nextptr.data);
            nextptr = nextptr.next;
        }

关于java - 将数组转换为 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19532307/

相关文章:

javascript - 我如何使用 selenium 和 java 捕获浏览器控制台日志

java - Files.walkFileTree 使用自定义 FileVisitor 泄漏目录描述符

java - 递归如何以相反的顺序打印链表元素?

c - 测试单链表性能时出现AddressSanitizer错误

java - JPanel 不想聚焦所以 KeyAdapter 不起作用

java接口(interface)方法从子类中删除

java - 二进制 XML 文件行 #12 : Error inflating class com. android.phone91.DialPadView

c - 段错误 - 队列不会初始化

c - 递归打印链表时出现段错误

java - Java链表实现中的入队操作中的赋值是如何工作的