I had basically no issue with linked lists in C++, but this is getting to me for some reason. I had a single node being printed out using the other classes in the package that were provided, but as I go on I just keep running into walls.
The code below is in shambles due to me tinkering around. I just have no idea where to go from here. As of now that is getting a null pointer exception.
Just for information: poll()
is just removing the current head and returning it, offer()
is adding to the rear. As of now the exception is at oldLast.next = last
in the offer method.
I am not asking for anyone to completely solve this. I just need some tips to progress.
public class FIFOQueue implements Queue {
//put your name as the value of the signature.
String signature = "name";
Node head = new Node(null);
Node pointer = head;
Node first;
Node last;
Node prev;
Node curr;
class Node {
Process process;
Node next;
Node(Process p) {
this.process = p;
this.next = null;
}
}
@Override
public void offer(Process p) {
if(head == null)
{
head = new Node(p);
first = head;
last = head;
}
else
{
Node oldLast = last;
Node newNode = new Node(p);
last = newNode;
oldLast.next = last;
}
}
@Override
public Process poll() {
if(isEmpty())
throw new NoSuchElementException();
Node oldPointer = first;
first = first.next;
head = first;
return oldPointer.process;
}
@Override
public boolean isEmpty() {
return head == null;
}
@Override
public String getSignature() {
return signature;
}
}
I think your core issue is here:
Node prev;
Node curr;
These are confusing you. Remove them.
Node prev;
- This should be in the Node
class. Node curr;
- This should be a local variable, not an instance variable. Also
Node head = new Node(null);
does not gel with
if(head == null)
{
head = new Node(p);
Either make head == null
mean the list is empty or something else - but be consistent.
(Posted on behalf of the OP) .
public void offer(Process p) {
if(head.process == null)
{
head = new Node(p);
first = head;
last = head;
}
last.next = new Node(p);
last = last.next;
}
This solved my issue. Can't believe I let this confuse me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.