Breadth First Search - Nullpointer Exception - java

I have implement a breadth first search for a school project where i get the start-node of a directional graph as an input and i have to return a Linked List containing the nodes in BFS order
This is my approach:
public List<Node> breadthFirstSearch(Node startNode){
//node list that has to be returned
LinkedList<Node> nodeList = new LinkedList<Node>();
resetState();
// TODO
//Queueu for the DfS Algorithm
Queue<Node> nodeQueue = new LinkedList<Node>();
//Add start node to NodeList and Queue
nodeQueue.add(startNode);
nodeList.add(startNode);
//While the Queue isn't empty
while(!nodeQueue.isEmpty()) {
Node v = nodeQueue.poll();
//iterate over adjacent nodes of current node and add them to Queue and List
for (Node w : getAdjacentNodes(v)) {
//don't add if already traversed node
if (!nodeList.contains(w)) {
nodeList.add(w);
nodeQueue.add(w);
}
}
}
return nodeList;
}
I have tested my function for several graphs and I didn't get any errors at my own tests. But when I upload my code to the schools servers and they run their tests i get following error: java.lang.NullPointerException in SearchTestng.testBFSCliqueNodes(SearchTestng.java:512)
I have been trying to reproduce the problem for hours now and none of my tutors seems to have an idea what could be causing the exception.
Does any of you have an idea what could possibly cause a null pointer exception here ?

Related

Linked List Java adding elements

I am learning linked lists in java and I have problem with the first element that is being enrolled twice. How to fix this problem. Here is my code :
if (head==null) {
head=new Node(data);
}
Node current=head;
while(current.getNext()!=null) {
current=current.getNext();
}
current.setNext(new Node(data));// how to change this line
}
https://pastebin.com/2PCvJmKT
You should add return, after adding first element.
if (head==null) {
head = new Node(data);
return;
}
I took code from link.
In pastebin, this code snippet is a part of your "insert"-function.
So in the code snippet you're looking upon the case "What if my LinkedList is empty? -> no elements in list -> no head
If that's the case, you just want to add the new data into the empty List as an new Node(data).
But what you're doing right now is: You're creating a new Node for an empty list, set that Node as Head and iterating through a list with just one element. That practically means, that you will never enter your while loop. After that you're adding a Node with the same data as the Head as its successor.

Reversing a singly linked list [Java]

I was wondering if someone could help explain how to reverse a singly linked list without creating new nodes or changing data in the existing nodes. I am trying to study for finals and we had this question on a previous test. They don't release answers to the coding portions of the test and I haven't been able to figure it out.
They told us the best way to reverse it was by using a "runner technique" which I believe I understand what that is. They described it as using two pointers or counters to run through a list and gather information but I'm not sure how to use that to reverse a singly liked list. I was able to brute-force code to reverse a list of length 2, 3, and 4 but I was unable to make a loop or do it recursively. Any code or an explanation on how to go about this would be appreciated, thank you.
You can derive the code by starting with the idea of merely - one by one - popping elements off the input list and pushing them onto an initially empty result list:
NODE reverse(NODE list) {
NODE result = null;
while (list != null) {
NODE head = <pop the first node off list>
<push head onto result>
}
return result;
}
The result will be the reverse of the input. Now substitute Java for the missing pieces
NODE reverse(NODE list) {
NODE result = null;
while (list != null) {
// pop
NODE head = list;
list = list.next;
// push
head.next = result;
result = head;
}
return result;
}
And you're done...
It depends on your implementation of the list, but I would recurse to the end and then reverse the references.
void Reverse(List pList) {
Reverse(pList, null, pList.First); // initial call
}
void Reverse(List pList, Node pPrevious, Node pCurrent) {
if (pCurrent != null)
Reverse(pList, pCurrent, pCurrent.Next); // advance to the end
else { // once we get to the end, make the last element the first element
pList.First = pPrevious;
return;
}
pCurrent.Next = pPrevious; // reverse the references on all nodes
}

Create objects dynamically and run BFS

I want to modify the code below for getting data from file dynamically and run the BFS. I have tried with loop but i am stuck on how i will make dynamic connection of the nodes using the anonymous objects.
Node nA=new Node("101");
Node nB=new Node("102");
Node nC=new Node("103");
Node nD=new Node("104");
Node nE=new Node("105");
//Create the graph, add nodes, create edges between nodes
Graph g=new Graph();
g.addNode(nA);
g.addNode(nB);
g.addNode(nC);
g.addNode(nD);
g.addNode(nE);
g.setRootNode(nA);
g.connectNode(nA,nB);
g.connectNode(nA,nC);
g.connectNode(nA,nD);
g.connectNode(nD,nE);
There will be an edge file containing the connected nodes.My sample code is below
String[] nodes = {"1","2","3","4"};
ArrayList<Node> Nodelist = new ArrayList<Node>();
//create node objects
for(String val : nodes) {
Nodelist.add(new Node(val));
}
//create graph nodes from array nodelist
Graph g = new Graph();
for(Node val : Nodelist) {
g.addNode(val);
}
g.setRootNode(Nodelist.get(0));
//then in loop to create connection between nodes from file in structure [101,102] , [102,103] ...
for(){
int[] arr = file.split(",")
g.connectNode(arr[0],arr[1])
}
My problem here is with the object names.I have tried using anonymous object and then adding them in addNode() But how i will create the connection of the nodes that will be read from file using the anonymous objects array.I don't know if i am clear what i am trying to achieve.
How i can add them in HashMap but using same key and array of values.I have tried with arraylist but saves only the last value.
What you're missing is having a way to find a node by it's value. You can have it by replacing the list of nodes with a map, where node's value is a key (assumption: each value is different).
Map<String, Node> nodeMap = new HashMap<>();
for (String val: nodes) {
nodeMap.put(val, new Node(val));
}
Later on to connect nodes get them from nodeMap by their value.

How a java class works with it's own reference type

I'm fairly new to JAVA and OOP and I'm currently following an academic course where I'm learning data structures and algorithms in java.
As I was learning about implementation of linked lists I've ran into a small problem of not understanding the code how to create a node when implementing a linked list(I'm familiar with constructors and bit of recursion ).
Code of the Node class as follows
public class Node {
public int info;
public Node next, prev;
public Node (int el) {
this (el,null,null);
}
public Node (int el,Node n,Node p){
info = el; next =n; prev=p;
}
}
I need to know what's happening behind the scene when the code executes(especially how the line3 works)and code of the List class is as follows
public class List {
private Node head, tail;
public List ( ){
head = tail = null;
}
public boolean isEmpty( ){
return head == null;
}
public void addToTail (int el) {
if (!isEmpty ( )) {
tail = new Node (el, null, tail);
tail.prev.next = tail;
}
else head = tail = new Node(el);
}
public int removeFromTail ( ){
int el = tail.info;
if (head == tail)
head = tail =null;
else
{
tail = tail.prev; tail.next = null;
}
return el;
}
}
(This example is given by the academy where I'm learning and I want to know how it works)
Please explain how the Node class works.
Ok let's start from the Node Class
public Node next, prev;
public Node (int el) {
this (el,null,null);
}
Here the objects next and prev are references to the next and previous nodes to the current node (which is your current object (this))
this (el,null,null);
It means you are creating a node which has no previous or next node. as you pass null, null for next and previous. Its similar to creating a head as head doesn't have next and previous nodes.
When you create the head you will never change it but you will change the next of the head the time when you create the second element in your list
When you create a tail of the linked list
public void addToTail (int el) {
if (!isEmpty ( )) {
tail = new Node (el, null, tail);
tail.prev.next = tail;
}
else head = tail = new Node(el);
}
here you first create a tail Node by tail = new Node (el, null, tail);
And then get the previous of tail and set the next element of the prev as the tail by doing tail.prev.next = tail;
Every time you add a new Node to the list you are calling addToTail(int e1) which updates the tail and updates the next of the old tail.
Let's suppose the entry point of your code is a call to:
List list = new List();
list.addToTail(1);
list.addToTail(2);
list.removeFromTail();
The first line of code execute the constructor into the list class, which simply set head and tail equal to null.
The second line of code add the method addToTail, and set the variable head and tail equal to new Node(1), which invoke the constructor having one parameter only in the Node class.
The third line of code add the method addToTail, but this time the list is not empty, so the script enters in the if statement and the node that you save with Node(2, null, tail). If you check this Node constructor with three parameters, tail (the node you added before which value was 1) will be set as the prev (previous) node associated with the current one.
The last line of code remove the 2nd node with the code tail = tail.prev; tail.next = null; and return the element you just removed.
firstly node in java its a specific type of variable, which can do the normal work of a variable and have an other information allow her to point on an other node in your case is public Node next, prev;
usually node are used in list ,think like train this is why you have addtootail here or removefromtail .
in this link you find a pretty quite explanation about that.
http://www.vias.org/javacourse/chap14_02.html
The Node class encapsulates the data, in this case an integer value named info.
Also, the List is implemented as a sequence of Nodes.
The reason for the next and prev values in Node is so that the node can be linked to its previous and next nodes in the list sequence. The only way to access a node in the list is to traverse the list, either forwards using the next reference, or backwards using the prev reference.
Note that lists do not support random access like an array would. To get to an element, you need to traverse the list in some direction.
I need to know what's happening behind the scene when the code executes(especially how the line3 works).
Please explain how the Node class works.
public Node next, prev;
Java variables that refer to object types are references, not values. The fields next and prev are not Node objects. No Node object contains other Nodes. Instead, next and prev reference Node objects stored separately.
If you're coming from C or C++, you can think of these references somewhat like pointers.
EDIT:
If you're instead asking about the construction of linked lists in general, your Node class represents a single node, containing a single item, in a doubly linked list. In a doubly linked list, each node refers to the node before and the node after.
See this illustration of a doubly linked list in this related wikipedia article.
The List is like a train. A Node is like a car in the train. The links are references between Nodes, which are similar to the coupling between train cars. The next and prev fields that you ask about are the links between nodes.
Logically, the List contains the entire train. Physically, your List references the head and tail of the train, so that it can travel over the Nodes from front-to-back, or back-to-front.

Unable to display nodes of the list properly starting from the tail to head

My insert method explanation:
I assigned the "next variable" of tail to hold the address of the old node. I assigned the tail with the new node inserted into the list.
I tried to display the list starting from the tail and going through the list until it reached the head.
Problem:
But the input displayed C which is not what I wanted. Display method is supposed to display C, B, A.
I even debug my code on paper. I don't know why the display is not retrieving the last address of the nodes linked in the linked list. It only retrieved the last node in the list and display only that last node in the list.
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.insert("A");
list.insert("B");
list.insert("C");
list.display();
}
public void insert(String data)
{
Link link = new Link(data);
// this code only executes the first time when the list has
// no node
if(head == null)
{
head = link;
tail= link;
}
// this code will execute when the linked list has one or more node
else
{
tail.next = tail;
tail = link;
}
}
public void display()
{
while(tail != null)
{
System.out.println(tail.data);
tail = tail.next;
}
}
You have created a singly linked list. The list has a head and tail, the links are from head to tail. A singly linked list by design has one direction "forward". With elements [a,b,c] the list is linked a->b->c. To print the elements in reverse order you have at least two options. Use recursion to print the elements c , b, a or implement a doubly linked list

Categories

Resources