Im a java beginner and I'm supposed to do an exercise for my class that involves creating a generic class that represents the Nodes of a graph. Either the method traverse or connect(or both) I implemented don't work properly. The graph is supposed to be an undirected graph, that means every connection between 2 points goes both ways.
Here is my code for the class Node:
import java.util.LinkedList;
public class Node <T>{
private T value;
private String name;
private LinkedList<Node <T>> adjacent;
public Node(String name, T value){
this.value=value;
this.name=name;
this.adjacent= new LinkedList<Node <T>>();
}
public String getName(){
return name;
}
public T getValue(){
return value;
}
public void setValue(T newValue){
this.value=newValue;
}
public void connect(Node<T> connectableNode){
this.adjacent.add(connectableNode);
connectableNode.adjacent.add(this);
//add() hängt das Argument ans Ende einer Liste
}
public void disconnect(Node<T> removableNode){
if (this.adjacent.contains(removableNode)){
this.adjacent.remove(removableNode);
removableNode.adjacent.remove(this);
}
}
public LinkedList<Node <T>> traverse(){
//Variablen definieren für BFS
LinkedList<Node <T>> graph = new LinkedList<Node <T>>();
LinkedList<Node<T>> queue = new LinkedList<Node <T>>();
Node <T> current;
Node <T> next;
int i;
//Startknoten ist erstes Element
graph.add(this);
queue.add(this);
while (queue.isEmpty()!=true){
current = queue.removeFirst();
//lasse for schleife durch alle Elemente der Adjazenzliste von current laufen
for (i=0; i<current.adjacent.size(); i++ ){
next=current.adjacent.removeFirst();
if (graph.contains(next)!=true){
graph.add(next);
queue.add(next);
}
}
}
return graph;
}
I'm supposed to create a graph that contains 7 nodes(named A to G) but I only get 4 connected Nodes as an Output:
(A,3) (G,9) (B,8) (F,17)
Also the Nodes should be traversed using the breadth-first search algorithm so the 4 Nodes I have are not in the right order.
import java.util.*;
class TestNodeClass{
public static void main(String[] args){
//Definitionen
LinkedList<Node <Integer>> course;
Iterator<Node<Integer>> iter;
Node <Integer> a = new Node <Integer>("A", 3);
Node <Integer> b = new Node <Integer>("B", 8);
Node <Integer> c = new Node <Integer>("C", 5);
Node <Integer> d = new Node <Integer>("D", 1);
Node <Integer> e = new Node <Integer>("E", 8);
Node <Integer> f = new Node <Integer>("F", 17);
Node <Integer> g = new Node <Integer>("G", 9);
a.connect(g);
a.connect(f);
b.connect(f);
b.connect(g);
f.connect(g);
c.connect(f);
c.connect(d);
d.connect(e);
course = a.traverse();
iter = course.iterator();
while (iter.hasNext()){
Node <Integer> current = iter.next();
String name = current.getName();
Integer value = current.getValue();
System.out.println("(" + name +","+ value + ")");
}
}
}
Would be great if someone could give me a hint or point out what's wrong, thanks!