2012-01-08 28 views
2
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,因为我到达列表的末尾,但我怎么可以阻止它这样做吗?的Java:NPE在循环链表:(

+2

你如何“到列表的末尾”获得一个循环列表? – 2012-01-08 01:39:36

+0

是的,它应该但那不是主要问题XD – svsav 2012-01-08 01:39:59

+0

尝试'c!= null && c.getNext()!=头'在你的第二个条件。 – Abbas 2012-01-08 01:40:27

回答

2

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