java.lang.NullPointerException in a little class - java

My java class comps up with a NullPointerException.Please help!
The error messages:
java.lang.NullPointerException at
RandomizedQueue.dequeue(52 line) at
RandomizedQueue$IndependantIterator.next (88 line) at
RandomizedQueue.main (104)
I have signed the line number in the end of the error code line.
import java.util.Iterator;
public class RandomizedQueue<Item> implements Iterable<Item> {
private int number=0;
private Node first=null;
private Node end=null;
private class Node {
Item item;
Node next=null;
Node last=null;
}
private Node Random() {
double r = Math.random();
int n = (int) (r*number);
if(n==0) n=1;
Node ob=first;
for(int i=0;i<(n-1);i++) {
ob = ob.next;
}
return ob;
}
public RandomizedQueue() {
Node empty=new Node();
}
public boolean isEmpty() {
return number==0;
}
public int size() {
return number;
}
public void enqueue(Item item) {
if(item==null) throw new NullPointerException();
number++;
if(first==null) {
first = new Node();
end = first;
first.item = item;
}
else {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
oldfirst.last = first;
}
}
public Item dequeue() {
Node ob=Random();
Item back=ob.item;
if(ob==end) {
end = ob.last;
ob.last.next=null; //52 line
}else if(ob==first) {
first=first.next;
first.last=null;
}
else {
ob.last.next=ob.next;
ob.next.last=ob.last;
}
return back;
}
public Node sample() {
return Random();
}
public Iterator<Item> iterator() {
return new IndepentRandomIterator();
}
private class IndepentRandomIterator implements Iterator<Item> {
private RandomizedQueue<Item> iq = new RandomizedQueue<Item>();
Node scan = first;
public IndepentRandomIterator() {
while(scan != null) {
iq.enqueue(scan.item);
scan=scan.next;
}
}
public boolean hasNext() {
return iq.number >0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if(iq.number==0) throw new java.util.NoSuchElementException();
return iq.dequeue(); //88
}
}
public static void main(String[] args) {
RandomizedQueue<String> test = new RandomizedQueue<String>();
test.enqueue("Luo");
test.enqueue("Jiebin");
test.enqueue("is");
test.enqueue("genious");
test.dequeue();
test.dequeue();
StdOut.println("Is it empty?"+test.isEmpty());
StdOut.println("Size: "+test.size());
StdOut.println("A sample: "+test.sample());
Iterator<String> it = test.iterator();
while(it.hasNext()) {
String s = it.next(); //104
}
}
}

It's because ob.last is null. The only time that end is set is when item is first in enqueue(). And last is never set there. In dequeue(), it goes to the if block if ob == end. Since end.last == null, therefore ob.last == null too and ob.last.next will throw NPE.

Related

Printing queue.peek() in Recursion prints irrelevant values

I am trying to check whether linked list is palindrome using queue.
solve() function returns true if linked list is palindrome.Equating q.peek with Node value returns false even after values are equal.
Tried printing q.peek() returns LList$Node#7852e922.
I did google it says like Queue node value is in use in previous functional call, did not get much.
public class LList {
private Node head = null;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public void push(int d) {
Node n = new Node(d);
n.next = head;
head = n;
}
public boolean solve(Node t, Queue q) {
if (t == null) {
return true;
}
q.add(t.data);
if (solve(t.next, q)) {
**System.out.println(q.peek());**//LList$Node#7852e922
if (q.peek().equals(t.data)) {
q.remove();
} else {
return false;
}
} else {
return false;
}
return true;
}
public static void main(String args[]) {
LList lList = new LList();
lList.push(5);
lList.push(4);
lList.push(3);
lList.push(4);
lList.push(5);
Queue<Integer> q = new LinkedList<Integer>();
System.out.println(lList.solve(lList.head, q));
}
}
As #Pramod said you adding a Node to queue here: q.dd(t)
In this method:
public boolean solve(Node t, Queue q) {
if (t == null) {
return true;
}
if (q == null) {
q = new LinkedList<Integer>();
}
q.add(t);
if (solve(t.next, q)) {
**System.out.println(q.peek());**//LList$Node#7852e922
if (q.peek().equals(t.data)) {
q.remove();
} else {
return false;
}
} else
return false;
return true;
}
Did you mean to q.add(t.data)?
You have declared Queue for Integer but you are trying to insert Node in the queue.
Change the comparison q.peek().equals(t.data) to q.peek().data == t.data and the type of queue to Queue<Node> q = new LinkedList<Node>()
Working code is(Comments added for the changes made):
public class LList {
//Made head static
private static Node head = null;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public void push(int d) {
Node n = new Node(d);
n.next = head;
head = n;
}
//changed the parameter type to Queue<Integer>
public boolean solve(Node t, Queue<Integer> q) {
if (t == null) {
return true;
}
if (q == null) {
q = new LinkedList<>();
}
q.add(t.data);
if (solve(t.next, q)) {
System.out.println(q.peek()); //prints 5 4 3 4 5
//changed the comparison condition.
if (q.peek() == t.data) {
q.remove();
} else {
return false;
}
} else
return false;
return true;
}
public static void main(String args[]) {
LList lList = new LList();
lList.push(5);
lList.push(4);
lList.push(3);
lList.push(4);
lList.push(5);
System.out.println(lList.solve(lList.head, null));
}
}
Output:
5
4
3
4
5
true

My implementation of a lock free linked list returns always an empty string on toString()

I am experimenting with lock free linked lists. This is my first shot but I have no idea why the toString method always returns an empty string even if I can see values in the debugger.
package com.linkedq;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
public class LinkedQueue <E> {
private static class Node <E> {
final E item;
final AtomicReference<Node<E>> next;
Node(E item, Node<E> next) {
this.item = item;
this.next = new AtomicReference<>(next);
}
#Override
public String toString() {
return item.toString();
}
}
private AtomicReference<Node<E>> head = new AtomicReference<>(new Node<E>(null, null));
private AtomicReference<Node<E>> tail = head;
public boolean put(E item) {
Node<E> newNode = new Node<E>(item, null);
while (true) {
Node<E> curTail = tail.get();
Node<E> residue = curTail.next.get();
if (curTail == tail.get()) {
if (residue == null) /* A */ {
if (curTail.next.compareAndSet(null, newNode)) /* C */ {
tail.compareAndSet(curTail, newNode) /* D */ ;
return true;
}
} else {
tail.compareAndSet(curTail, residue) /* B */;
}
}
}
}
public void remove(E item) {
Node<E> current = this.head.get().next.get();
Node<E> next = null;
while (current != null) {
next = current.next.get();
if (next.equals(item)) {
if (!current.next.compareAndSet(next, next.next.get())) {
// some other thread changed the list, do a retry
remove(item);
}
}
current = next;
}
}
#Override
public String toString() {
Node<E> current = head.get().next.get();
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current).append(", ");
current = current.next.get();
}
return sb.toString();
}
public static void main(String[] args) throws InterruptedException {
final ExecutorService es = Executors.newFixedThreadPool(10);
final LinkedQueue<Integer> q = new LinkedQueue<>();
for (int i=0; i<10000; i++) {
es.execute(new Inserter(q, i));
}
// es.shutdown();
// es.awaitTermination(1L, TimeUnit.HOURS);
System.out.println("FIN" + q);
}
private static class Inserter implements Runnable {
private final LinkedQueue<Integer> q;
private final int value;
public Inserter(LinkedQueue<Integer> q, int value) {
this.q = q;
this.value = value;
}
#Override
public void run() {
q.put(value);
System.out.println("q = " + q);
}
}
}
At least one obvious error is that your head and tail are actually the same AtomicReference object, so when you update the tail, the head is updated as well. Use
private AtomicReference<Node<E>> head = new AtomicReference<>(new Node<E>(null, null));
private AtomicReference<Node<E>> tail = new AtomicReference<>(head.get());
Another obvious mistmatch is that the first element you add inside the tail and the head:
tail.compareAndSet(curTail, newNode) ;
While when you read, you start printing from the next of the head:
Node<E> current = head.get().next.get();
So even without having multiple threads, etc, just adding one element and printing the list does not work. Add unit tests to verify the behavior!

Issue returning dequeued value from ImmutableQueue

I am implementing an immutable queue using the following code :
import java.util.NoSuchElementException;
import java.util.Queue;
public class ImmutableQueue<E> {
//Two stacks are used. One is to add items to the queue(enqueue) and
//other is to remove them(dequeue)
E returnedItem;
private ImmutableQueue(ReversableStack<E> order, ReversableStack<E> reverse) {
this.order = order;
this.reverse = reverse;
}
//initially both stacks are empty
public ImmutableQueue() {
this.order = ReversableStack.emptyStack();
this.reverse = ReversableStack.emptyStack();
}
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
public ImmutableQueue<E> dequeue() {
if (this.isEmpty())
throw new NoSuchElementException();
if (!this.reverse.isEmpty()) {
returnedItem = this.reverse.head;
return new ImmutableQueue<E>(this.order, this.reverse.tail);
} else {
returnedItem = this.reverse.head;
return new ImmutableQueue<E>(ReversableStack.emptyStack(),
this.order.getReverseStack().tail);
}
}
private static class ReversableStack<E> {
private E head; //top of original stack
private ReversableStack<E> tail; //top of reversed stack
private int size;
//initializing stack parameters
private ReversableStack(E obj, ReversableStack<E> tail) {
this.head = obj;
this.tail = tail;
this.size = tail.size + 1;
}
//returns a new empty stack
public static ReversableStack emptyStack() {
return new ReversableStack();
}
private ReversableStack() {
this.head = null;
this.tail = null;
this.size = 0;
}
//Reverses the original stack
public ReversableStack<E> getReverseStack() {
ReversableStack<E> stack = new ReversableStack<E>();
ReversableStack<E> tail = this;
while (!tail.isEmpty()) {
stack = stack.push(tail.head);
tail = tail.tail;
}
return stack;
}
public boolean isEmpty() {
return this.size == 0;
}
public ReversableStack<E> push(E obj) {
return new ReversableStack<E>(obj, this);
}
}
private ReversableStack<E> order;
private ReversableStack<E> reverse;
private void normaliseQueue() {
this.reverse = this.order.getReverseStack();
this.order = ReversableStack.emptyStack();
}
public E peek() {
if (this.isEmpty())
throw new NoSuchElementException();
if (this.reverse.isEmpty())
normaliseQueue();
return this.reverse.head;
}
public boolean isEmpty() {
return size() == 0;
}
//returns the number of items currently in the queue
public int size() {
return this.order.size + this.reverse.size;
}
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue=newQueue.enqueue(5);
newQueue=newQueue.enqueue(10);
newQueue=newQueue.enqueue(15);
//newQueue = newQueue.dequeue();
//System.out.print(newQueue);
int x = newQueue.peek();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
}
The dequeue function does not seem to return the removed item, it only removes it. This the commented line by the way. How do I access the removed item ?
I have created a variable of type E in the main class. Now how do I access it in main and get the dequed value ?
Thanks

Null pointer exception in Deque implementation

I am learning Java, and implementing a Deque data structure. This is the Node class:
import java.util.*;
public class Deque<Item> implements Iterable<Item> {
private Node sentinel;
private class Node {
Item item;
Node next;
Node previous;
Node(Item value) {
item = value;
next = this;
previous = this;
}
}
public Deque(Item item) // construct an empty deque
{
Node sentinel = new Node(item);
}
public boolean isEmpty() // is the deque empty?
{
return (size() == 0);
}
public int size() // return the number of items on the deque
{
System.out.println("size");
if (sentinel.next == sentinel) {
System.out.println("empty");}
return 0;
// }
// int count = 0;
// Node temp = sentinel;
// while (temp != sentinel)
// {
// count += 1;
// temp = temp.next;
// }
// return count;
}
public void addFirst(Item item) // insert the item at the front
{
if (item == null) {
throw new java.util.NoSuchElementException();
}
Node a = new Node(item);
if (isEmpty())
{
System.out.println("Hello world");
sentinel.next = a;
a.previous = sentinel;
}
else
{
sentinel.next.previous = a;
sentinel.next = a;
a.previous = sentinel;
}
}
public void addLast(Item item) // insert the item at the end
{
if (item == null)
throw new java.util.NoSuchElementException();
Node a = new Node(item);
sentinel.previous = a;
a.next = sentinel;
}
public Item removeFirst() // delete and return the item at the front
{
if (isEmpty())
throw new UnsupportedOperationException();
Item value = sentinel.next.item;
sentinel.next = sentinel.next.next;
sentinel.next.previous = sentinel;
return value;
}
public Item removeLast() // delete and return the item at the end
{
if (isEmpty())
throw new UnsupportedOperationException();
Item value = sentinel.previous.item;
sentinel.previous = sentinel.previous.previous;
sentinel.previous.next = sentinel;
return value;
}
public Iterator<Item> iterator() // return an iterator over items in order from front to end
{
return new DequeueIterator();
}
private class DequeueIterator implements Iterator<Item>
{
private Node current = sentinel;
public boolean hasNext() {
return current != null;
}
public void remove() {}
public Item next() {
Item value = current.item;
current = current.next;
return value;
}
}
public static void main(String[] args) // unit testing
{
System.out.println(Thread.currentThread().getStackTrace());
Deque<Integer> d = new Deque<Integer>(0);
System.out.println(d.isEmpty());
System.out.println(Thread.currentThread().getStackTrace());
// d.addFirst(10);
// System.out.println(d.size());
// System.out.println(d.removeLast());
}
}
Then when checking the size of the Deque as following:
public class Deque<Item> implements Iterable<Item> {
public Deque() // construct an empty deque
{
Node sentinel = new Node(null);
if (sentinel.next == sentinel)
System.out.println("empty");
}
}
The compiler error is NullPointerException. Is it due to the initialization of Node(null)? If yes, how can I input a zero value for the generic Item?
Stacktrace:
java.lang.NullPointerException
at Deque.size(Deque.java:29)
at Deque.isEmpty(Deque.java:24)
at Deque.main(Deque.java:111)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
And line 29 is:
if (sentinel.next == sentinel)
You're declaring a local variable called sentinel and assigning it instead of using the instance field and assigning it.
public Deque(Item item) // construct an empty deque
{
Node sentinel = new Node(item);
}
should be
public Deque(Item item) // construct an empty deque
{
this.sentinel = new Node(item);
}
otherwise the instance variable sentinel remains null and causes a NullPointerException when you try to dereference it
public int size() // return the number of items on the deque
{
System.out.println("size");
if (sentinel.next == sentinel) { // here
System.out.println("empty");
}
return 0;
}
If you get a NullPointerException on the following line:
if (sentinel.next == sentinel)
then the only cause can possibly be that sentinel is null. This is because in the constructor for Deque, you are creating a new variable called sentinel, not using the one in the class.

Creating queue from two stacks

Can someone explain what am I doing wrong here ?
I am trying to create a queue from two stacks as per a book exercise. I get error "Stack Underflow" from the peek function. But everything seems right to me :P Please explain. Thanks!
//Program to implement Queue using two Stacks.
import java.util.NoSuchElementException;
public class Ex3_5_Stack {
int N;
int countOfNodes=0;
private Node first;
class Node {
private int item;
private Node next;
}
public Ex3_5_Stack() {
first=null;
N=0;
}
public int size() {
return N;
}
public boolean isEmpty() {
return first==null;
}
public void push(int item){
if (this.countOfNodes>=3) {
Ex3_5_Stack stack = new Ex3_5_Stack();
stack.first.item=item;
N++;
} else {
Node oldfirst = first;
first = new Node();
first.item=item;
first.next=oldfirst;
N++;
}
}
public int pop() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
int item = first.item;
first=first.next;
return item;
}
public int peek() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
return first.item;
}
}
And MyQueue file
public class Ex3_5_MyQueue {
Ex3_5_Stack StackNewest,StackOldest;
public Ex3_5_MyQueue() {
super();
StackNewest = new Ex3_5_Stack();
StackOldest = new Ex3_5_Stack();
}
public int size() {
return StackNewest.size()+StackOldest.size();
}
public void add(int value) {
StackNewest.push(value);
}
private void transferStack() {
if (StackOldest.isEmpty()) {
while (StackNewest.isEmpty()) {
StackOldest.push(StackNewest.pop());
}
}
}
public int peek() {
this.transferStack();
return StackOldest.peek();
}
public int remove() {
this.transferStack();
return StackOldest.pop();
}
public static void main(String[] args) {
Ex3_5_MyQueue myQueue = new Ex3_5_MyQueue();
myQueue.add(4);
myQueue.add(3);
myQueue.add(5);
myQueue.add(1);
System.out.println(myQueue.peek());
}
}
In transferStack(), you're missing an exclamation mark. It should be:
private void transferStack(){
if(StackOldest.isEmpty()){
while(!StackNewest.isEmpty()){ // you forgot it here
StackOldest.push(StackNewest.pop());
}
}
}

Categories