Я понятия не имею, почему у меня есть Исключение ошибки в потоке "основной" java.lang.NullPointerException - PullRequest
0 голосов
/ 03 февраля 2019

Я пытался использовать reverseBystack, reverseBylink и удалить ... но я не знаю, почему, когда я использую эти функции, он имеет ошибку, подобную этой.

Exception in thread "main" java.lang.NullPointerException
at LinkedQueue$Node.access$200(LinkedQueue.java:44)
at LinkedQueue.reverseBylink(LinkedQueue.java:185)
at LinkedQueue.main(LinkedQueue.java:238)

void reverseByStack () - Этот метод обращает вспятьпорядок элементов в связанном списке (первый становится последним, а последний становится первым) с использованием структуры данных стека enter code here ture` • void reverseByLinks () - этот метод также меняет порядок элементов в связанном списке.Не следует создавать новый список или использовать стек.Следует только изменить порядок узлов, изменив следующие значения для каждого узла в списке.• int remove (Item item) - этот метод сканирует очередь на наличие вхождений элемента и удаляет их из очереди.Он возвращает количество элементов, удаленных из очереди.

это то, что я хочу сделать.

enter code here public class LinkedQueue<Item> implements Iterable<Item> {
private int N;         // number of elements on queue
private Node first;    // beginning of queue
private Node last;     // end of queue

// helper linked list class
private class Node {
    private Item item;
    private Node next;
}

public LinkedQueue() {
    first = null;
    last  = null;
    N = 0;
    assert check();
}


public boolean isEmpty() {
    return first == null;
}


public int size() {
    return N;     
}


public Item peek() {
    if (isEmpty()) throw new NoSuchElementException("Queue 
         underflow");
    return first.item;
}


public void enqueue(Item item) {
    Node oldlast = last;
    last = new Node();
    last.item = item;
    last.next = null;
    if (isEmpty()) first = last;
    else           oldlast.next = last;
    N++;
    assert check();
}


public Item dequeue() {
    if (isEmpty()) throw new NoSuchElementException("Queue 
        underflow");
    Item item = first.item;
    first = first.next;
    N--;
    if (isEmpty()) last = null;   // to avoid loitering
    assert check();
    return item;
}


public String toString() {
    StringBuilder s = new StringBuilder();
    for (Item item : this)
        s.append(item + " ");
    return s.toString();
} 


private boolean check() {
    if (N == 0) {
        if (first != null) return false;
        if (last  != null) return false;
    }
    else if (N == 1) {
        if (first == null || last == null) return false;
        if (first != last)                 return false;
        if (first.next != null)            return false;
    }
    else {
        if (first == last)      return false;
        if (first.next == null) return false;
        if (last.next  != null) return false;

        // check internal consistency of instance variable N
        int numberOfNodes = 0;
        for (Node x = first; x != null; x = x.next) {
           numberOfNodes++;
        }
        if (numberOfNodes != N) return false;

        // check internal consistency of instance variable last
        Node lastNode = first;
        while (lastNode.next != null) {
           lastNode = lastNode.next;
        }
        if (last != lastNode) return false;
    }

    return true;
}
void reverseBystack(){
    Stack<Item> s = new Stack<>();
    Item item;
    while (s.isEmpty() != true){
        item = dequeue();
        s.push(item);
    }
    while(s.isEmpty() != true){
        item = s.pop();
        enqueue(item);

    }


}

 void reverseBylink() {
    Node prev = null;
    Node current = this.first;
    Node next = null;
    while (current != null) {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
    prev.next = current.next;
 }



int remove(Item item){

    Node cur = first;
    Node prev = last;
            while(cur != null) {
                if(cur.item.equals(item))
                    System.out.println(cur.item);
            }
            cur = cur.next;
            prev = cur.next;
            return 0;
}






public Iterator<Item> iterator()  {
    return new ListIterator();  
}

private class ListIterator implements Iterator<Item> {
    private Node current = first;

    public boolean hasNext()  { return current != null;                  
     }
    public void remove()      { throw new 
    UnsupportedOperationException();  }

    public Item next() {
        if (!hasNext()) throw new NoSuchElementException();
        Item item = current.item;
        current = current.next; 
        return item;
    }
  }


/**
 * Unit tests the <tt>LinkedQueue</tt> data type.
 */
public static void main(String[] args) {
    LinkedQueue<String> q = new LinkedQueue<String>();

    while (!StdIn.isEmpty()) {
        String item = StdIn.readString();
        if (!item.equals("-"))  q.reverseBylink();
        else if (!q.isEmpty()) StdOut.print(q.dequeue() + " ");

    }

    StdOut.println("(" + q.size() + " left on queue)");
  }
 }
...