-5

This is my add method for my Josephus class in which I am supposed to be using a Circular Linked List. I am getting null pointer exceptions in a few areas in my class but it is all because of this method. Can anyone see any OBVIOUS mistakes from looking at this code?

/** Inserts the specified element in the list at the
     last position
     @param dataItem the element to add
   */
 // Complexity O(1)
 @SuppressWarnings({ "unchecked" })
public void add(E dataItem) {
    Node <E> node = new Node <E> (dataItem,null,null);
    if (count == 0){ // list is empty
        head = node.previous= node;  
    }

    else {
       head.previous.next = node;
       node.previous = head.previous;
       head.previous = node;
    }
    count++; 
    }

Full code: http://pastebin.com/k4Hmbqmw

4

2 回答 2

6

是的,您需要else用花括号将您的部分括起来:

public void add(E dataItem) {
    Node <E> node = new Node <E> (dataItem, null, null);
    if (count == 0) { // list is empty
        head = node.previous= node ;  
    } else {
       (head.previous).next = node;
       node.previous = head.previous;
       head.previous = node;
    }
    count++;
}

否则,每次都会执行最后三行,而不仅仅是最后一行。

于 2012-10-26T21:49:11.207 回答
1

if/else 块周围没有花括号

于 2012-10-26T21:49:28.843 回答