【发布时间】: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 && c.getNext()。 -
我将其更改为 'c != null && c.getNext() != head' 但现在它只显示链接列表中的最终值。例如,如果我的 LL 是 1 2 3 4 5 6 并且我向右旋转 3,它只会打印 4 5 6。
标签: java list linked-list