I am trying to build a linked list as is shown below:
**list-> [C] - [B] - [A] -> NULL**
Here is my main:
import java.util.*;
class LinkedListF
{
public static void main (String [] args)
{
Node aNode = new Node ("A", null);
Node bNode = new Node ("B", aNode);
Node list = new Node ("C",bNode);
DynamicList dynamicList = new DynamicList();
dynamicList.insertFirst("A");
dynamicList.insertFirst("C");
dynamicList.insertAfter(list, "B");
//the line above is where I am struggling with.
System.out.println(dynamicList.getList().getInfo());
System.out.println(dynamicList.getList().getNext().getInfo());
System.out.println(dynamicList.getList().getNext().getNext().getInfo());
}
}
The problem I am having now, as I mark in the codes, is when the code "dynamicList.insertAfter(list, "B")
" runs, it does not insert "B" after the Node "list" in the dynamicList that I construct. I am very confused about what is happening here.
My output looks like this:
----jGRASP exec: java LinkedListF
C
A
Exception in thread "main" java.lang.NullPointerException
at LinkedListF.main(LinkedListF.java:27)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
The line 27 is my third System.out.print statement.
Below is the insertAfter method in my DynamicList class:
public void insertAfter(Node p, String x)
{
if (isEmpty())
{
System.out.println("VOID INSERTION.");
System.exit(1);
}
Node q = new Node (x, p.getNext());
p.setNext(q);
}
Below is the Node class that I use to construct each node:
class Node
{
private String data;
private Node next;
public Node (String data, Node next)
{
this.data = data;
this.next = next;
}
String getInfo()
{
return data;
}
Node getNext()
{
return next;
}
void setInfo(String data)
{
this.data = data;
}
void setNext(Node next)
{
this.next = next;
}
}