2012-01-08 56 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,並確保您從初始列表中獲取第一個元素。