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在循環鏈表:(
你如何「到列表的末尾」獲得一個循環列表? – 2012-01-08 01:39:36
是的,它應該但那不是主要問題XD – svsav 2012-01-08 01:39:59
嘗試'c!= null && c.getNext()!=頭'在你的第二個條件。 – Abbas 2012-01-08 01:40:27