【问题标题】:Java: NPE in Circular Linked List :(Java:循环链表中的 NPE :(
【发布时间】:2012-01-08 01:37:00
【问题描述】:
import javax.swing.JOptionPane;

public class RotateArrayCircularLL
{
    private Node head=null;   

    public void init()
    {

       int choice = 0;

        while (choice != -1){
        choice = Integer.parseInt(JOptionPane.showInputDialog("Enter -1 to stop loop, 1 to continue"));    

        if(choice == -1)
            break;

        inputNum();

      }
      printList();
    }

    public void inputNum()   
    {
        Node n;
        Node temp;
        int k;

        k = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number:"));
        n = new Node(k);       

         if (head == null) {
            head = n;            
         } else {            
            temp = head;
            while (temp.getNext() != null)
                temp = temp.getNext();

            temp.setNext(n);                
        }       

    } 

    public void printList()  
    {
        Node temp = head;

        int count =  Integer.parseInt(JOptionPane.showInputDialog("Enter the value to shift to the right"));

        for (int i = 1; i <= count; i++) // Rotates the head
            temp = temp.getNext();

        for (Node c = temp; c != null && c.getNext() != head; c= c.getNext()){ // Prints the new LL
            System.out.print(c.getInfo());   
        }
    }     
}

我在第二个 for 循环中得到 NPE。我知道它给了我一个 NPE,因为我到达了列表的末尾,但是我怎样才能阻止它这样做呢?

【问题讨论】:

  • 循环列表如何“到达列表末尾”?
  • 是的,但那不是主要问题 XD
  • 在第二个条件中尝试 'c != null && c.getNext() != head'。
  • @Abbas:鉴于这里隐含的结构,不应该是c.getNext() != null &amp;&amp; c.getNext()
  • 我将其更改为 'c != null && c.getNext() != head' 但现在它只显示链接列表中的最终值。例如,如果我的 LL 是 1 2 3 4 5 6 并且我向右旋转 3,它只会打印 4 5 6。

标签: java list linked-list


【解决方案1】:

从您看到的行为看来,您的链接列表中的一个节点正在返回 null 而不是列表的下一个元素。猜测一下,我建议您列表的最后一个节点可能不指向您列表的第一个节点。因此,正如 Hovercraft Full Of Eels 所暗示的那样,您实际上并没有正确的循环链表。如果您可以发布显示temp 填充方式的代码,则可以为您的问题提供更具体的解决方案。否则,您需要将 getNext() 返回 null 的情况视为特殊情况,并确保您改为从初始列表中获取第一个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2014-12-28
    相关资源
    最近更新 更多