Java Queues and Stacks - java

I have a small problem that I'm hoping someone could help me with.
This is an assignment, so I am not supposed to use classes imported from the java API nor am I supposed to do this in any other way (arraylist would have made this much easier.)
I created a Queue class and a Stack class.
I am trying to retrieve the head of the Queue, and add it to the Stack.
I am guessing I will need to create a method that somehow gets the value of the head of the list and stores it so I can use it.
For example, if I enqueued " bob", "jack", and "jill" to the Queue in that order, it will look like:
bob
jack
jill
I want to dequeue bob from the queue list, but add him to the head of the Stack list, but I can't figure out how. I'm sorry if my question is not very precise, I'm having problems wording what I really need. If any other information is needed I will update my post. Thanks for any help.
Here is my Queueclass:
(LL is my Link List class)
public class Queue<T extends Comparable<T>> {
LL<T> theQueue;
public Queue() {
theQueue = new LL<T>();
}
public boolean isEmpty() {
return theQueue.isEmpty();
}
public void enqueue(T value) {
theQueue.insertTail(value);
}
public T dequeue() throws QueueException {
T retval = null;
try {
retval=theQueue.deleteHead();
}catch (LLException e) {
throw new QueueException ("Queue is empty");
}
return retval;}
public String toString() {
return theQueue.toString();
}}
And my Stack Class:
public class Stack<T extends Comparable<T>>{
LL<T> theStack;
public Stack()
{
theStack = new LL<T>();
}
public boolean isEmpty()
{
return theStack.isEmpty();
}
public void push(T value)
{
theStack.insertHead(value);
}
public T pop() throws StackException
{
T retval = null;
try
{
retval = theStack.deleteHead();
}
catch (LLException e)
{
throw new StackException("Stack Underflow");
}
return retval;
}
public boolean isFull()
{
return false;
}
public String toStrin()
{
return theStack.toString();
}
Main Class:
public static void main(String[] args) {
Stack <String> hired = new Stack<String>();
Stack <String> fired = new Stack<String>();
Queue <String> apps = new Queue<String>();
String temp;
for (int i = 0; i < 1000; i++) {
System.out.println("Enter the number of the action to perform:");
System.out.println("1. Accept Application");
System.out.println("2. Hire");
System.out.println("3. Fire");
System.out.println("4. Exit");
Scanner kb = new Scanner(System.in);
int key = kb.nextInt();
switch (key) {
case 1:
System.out.println("Enter applicant's name and ID separated by semi-colon:");
String applicant = kb.next() + "\n";
System.out.println("You entered " + applicant);
apps.enqueue(applicant);
break;
case 2:
try{
temp = apps.dequeue();
} catch (QueueException s) {
}
try{ apps.dequeue(); }
catch (QueueException s){
System.out.println("Queue is empty");}
hired.push(temp);
case 3:
System.out.println();
case 4: System.out.println("Bye");
System.exit(0);
}
}
So it won't let me assign apps.dequeue() to temp without the try and catch. but then when I do hired.push(temp); I get an error saying temp may have not been initialized.

I think what you want to do is "To dequeue "bob" from the Queue and add it to the Stack", isn't it?
So I think you have already tell what to do:
Queue<String> q = new Queue<String>();
Stack<String> s = new Stack<String>();
// ... enqueue three strings
String temp = q.dequeue();
s.push(temp);
Yes - this task has nothing to do with the implementation of your Queue and Stack class. It's only about using the interface. As long as you have implemented them correctly, these code work.
EDIT
So maybe this is what you want:
String temp = ""; // explicitly initialize
try {
temp = q.dequeue();
s.push(temp);
} catch {
}
I put both dequeue and push in try block: if dequeue fails, nothing is to be pushed. Is this right for you ?

Use iterator (if you need to push value from a random position of queue into stack). For your assignment, simply dequeue method should work fine as pointed in another answer.
Before calling the dequeue method, call this iterator and check if hasNext(). if true, get the value using iterator.next() and store it.
Now you have the value in 'head' position. Now call dequeue method and delete the head value. Now simply push your stored value into stack

Related

How to create a search method inside an array

Good morning, I have the following specification:
"The searchAccount () method must verify the existence of the current account passed as a parameter in the set of current currents existing in the bank and stored in the vector."
I have implemented the following solution.
public boolean searchAccount(BankAccount ba) {
boolean found=false;
int count=0;
while(count<=accounts.length-1) {
if(accounts[count]!=null &&(accounts[count].getCode().equals(ba.getCode())))
found=true;
else
found=false;
count++;
}
return found;
}
Note that accounts is an array defined inside the class where the searchAccount () method is present. However, this solution gives me problems at runtime. Everything is fine when compiling.
In particular given the following main () method:
public static void main(String[] args) {
// print a large HTML header
System.out.println("<h4>-- Bank account exercise --</h4>");
// create 5 objects of type BankAccount
BankAccount c1 = new BankAccount("001",5);
BankAccount c2 = new BankAccount("002",10);
BankAccount c3 = new BankAccount("003",15);
BankAccount c4 = new BankAccount("004",20);
BankAccount c5 = new BankAccount("005",25);
Bank b = new Bank("B001");
b.addAccount(c1);
b.addAccount(c2);
b.addAccount(c3);
b.addAccount(c4);
b.addAccount(c5);
System.out.println("Search bank account having code " +
c4.getCode() + ": ");
System.out.println((b.searchAccount(c4))?"Found":"Not found");
System.out.println("c1.equals(c2)?" + (c1.equals(c2)));
BankAccount c6 = new BankAccount("001",29);
System.out.println("c1.equals(c6)?" + (c1.equals(c6)));
//System.out.println(b);
}
By running I get:
<h4>-- Bank account exercise --</h4>
Search bank account having code 004:
Not found
c1.equals(c2)?false
c1.equals(c6)?true
I don't know why the searchAccount () method doesn't find the C4 object.
What happens when you find a match? You set found to true. Then, you continue searching. When there are more elements, you'll again set (reset) found to false.
You must break and return the result when you find a match (short-circuiting the search).
while(count <= accounts.length-1) {
if(accounts[count] != null &&(accounts[count].getCode().equals(ba.getCode()))) {
found = true;
break;
}
}
return found;
Or, you can remove the found variable and just return.
while(count <= accounts.length-1) {
if(accounts[count] != null &&(accounts[count].getCode().equals(ba.getCode()))) {
return true;
}
}
return false;
Try returning the true value instead of saving it using found variable. So write return true;
Your searchAccount method actually finds the target account, but just continues with the loop, so the next iteration will cause found to be false.
As the other answers mention, you need to break the search when the account is found.
Here are two other alternatives to the search.
Using for-loop:
public boolean searchAccount2(BankAccount ba) {
for(BankAccount account : accounts) {
if(account != null && account.getCode().equals(ba.getCode())) {
return true;
}
}
return false;
}
Using streams:
public boolean searchAccount3(BankAccount ba) {
return Arrays.asList(accounts).stream().filter(Objects::nonNull).anyMatch(b -> b.getCode().equals(ba.getCode()));
}
Update
To test the above code I implemented rudimentary Bank and BankAccount classes and ran your code above, but adding searchAccount2 and searchAccount3:
//...
System.out.println((b.searchAccount(c4))?"Found":"Not found");
System.out.println((b.searchAccount2(c4))?"Found":"Not found");
System.out.println((b.searchAccount3(c4))?"Found":"Not found");
//...
Accounts are assumed to be an array in the Bank class:
private BankAccount[] accounts
This is the output:
<h4>-- Bank account exercise --</h4>
Search bank account having code 004:
Not found
Found
Found
c1.equals(c2)?false
c1.equals(c6)?false
EDIT - addAccount()
Here is your addAccount (as posted in the comment) formatted:
public void addAccount2(BankAccount ba) {
//Il metodo addAccount() deve aggiungere il conto corrente passato
// come parametro al vettore dei conti correnti presente nella banca,
// se non e' già presente.
if (!searchAccount(ba)) {
for (int i = 0; i < accounts.length; ++i) {
if (accounts[i] == null) {
accounts[i] = ba;
// PROBLEM HERE!!!
}
}
}
}
This method will add the given account (ba) to every position in the array because you do not stop the loop at any time.
You need a return statement where I indicated the "PROBLEM HERE!!!":
public void addAccount2(BankAccount ba) {
if (!searchAccount(ba)) {
for (int i = 0; i < accounts.length; ++i) {
if (accounts[i] == null) {
accounts[i] = ba;
return;
}
}
}
}
Otherwise, after you add the first account (to every position) there is no more room to add further accounts.
The better option for this task will be usage of Map for store your accounts objects.
Something like this:
public class Bank {
private Map<String,Account> accounts = new HashMap<>();
public void addAccount(Account account){
accounts.put(account.getCode(),account);
}
public boolean searchAccount(Account account){
return accounts.containsKey(account.getCode());
}
}
Ok, so maybe it's my addAccount () method that's wrong. I'll bring it back here:
public void addAccount(BankAccount ba) {
if(!searchAccount(ba))
for(int i=0;i<=accounts.length-1;i++)
if(accounts[i]==null)
accounts[i]=ba;
}

Loop through a LinkedList

I'm trying to get a LinkedList from my buffer class (BufferCharacter) and then loop through every element in the LinkedList in the Reader class. But when I try return the LinkedList in the get() method in BufferCharacter class I then cannot loop through it in the Reader class. I've tried to loop through the List in the Buffer class and then return each element from there but that doesn't work either.
Any help is highly appreciated!
public class CharacterBuffer {
private char ch;
private LinkedList buffer = new LinkedList();
private boolean filled;
public void put(char ch) {
buffer.addLast(ch);
}
public void filled() {
filled = true;
}
public Object get() throws InterruptedException {
while (buffer.isEmpty()) {
// wait();
return "Waiting";
}
return buffer;
}
public synchronized void putSync(char ch) {
buffer.addLast(ch);
}
public synchronized Object getSync() throws InterruptedException {
while (buffer.isEmpty()) {
// wait();
return "---------";
}
for(int i = 0; i<buffer.size(); i++){
System.out.println(buffer.get(i));
}
return buffer;
}
public int size(){
return buffer.size();
}
}
public class Reader extends Thread {
private GUIMutex gui;
private CharacterBuffer buffer;
private boolean isSynced;
public Reader(GUIMutex gui, CharacterBuffer buffer, boolean isSynced) {
this.gui = gui;
this.buffer = buffer;
this.isSynced = isSynced;
}
public void run() {
String data = "test";
while (true) {
try {
// data = buffer.get();
if (isSynced) {
gui.setReaderText(buffer.getSync() + "\n");
} else {
for(int i = 0; i<buffer.get().size(); i++){
gui.setReaderText(i);
}
gui.setReaderText(buffer.get() + "\n");
}
Thread.sleep(700);
} catch (InterruptedException e) {
}
}
}
}
I think you don't understand what you are talking about; so lets try to shed some light here.
In the end, you are talking about some kind of "collection" class that contains multiple elements; in your case a LinkedList. The thing is: in order to make use of such a class, you need a clear understanding of the APIs you intend to provide.
You figured that you want to use that buffer to store individual char values, that you add using putSync().
But then ... what exactly is getSync() supposed to do?
In your case, you are simply returning the buffer, and that is probably wrong.
Instead, you want to have methods like:
synchronized boolean hasNext()
and
synchronized char getNext()
A user of your class can call the first method to figure: are there other chars; and if so, the second method returns those values.
That would a first, simple way to improve your code. A more reasonable way would be that you implement a method getIterator() that would return an object implementing the Iterator interface.
Other things to note: if you are using the "built-in" LinkedList; please understand that this class supports generics!
Thus you should be using it like:
private final List<Character> buffer = new LinkedList<>();
to get all the benefits from using strongly typed collections!
EDIT: upon your comments, I think using a LinkedList is simply the wrong approach here.
Instead of using a List, you want to use a Queue, like:
private final Queue<Character> buffer = new ConcurrentLinkedQueue<>();
That class gives you that functionality that one party can add elements at the queue tail; whereas another party removes elements from the queue head.
Extra bonus: that class is doing the synchronisation work for you already, so you don't need to care about that!
Use StringBuilder instead
StringBuilder sb = new StringBuilder(128);
// add chars using sb.append(char)
for (int i = 0, n = sb.length(); i < n; i++)
{
char c = sb.charAt(i);
}
or
String s = sb.toString();

Retrive and compare int value from an ArrayList

good night. I'm trying to retrieve and compare an int variable value from an ArrayList (if that is possible) but no matter what I do it never works. I already tried methods like contains(), get() and others. My logic is really bad I guess, could someone help me ? Please?
public class Obras extends Books implements ILibrary {
protected ArrayList<Obras> ListObra = new ArrayList<Obras>();
protected String typeObra;
protected String statusBorrow;
protected int ISBNuser;
Scanner userInput = new Scanner(System.in);
Scanner tipoInput = new Scanner(System.in);
public void createnewObra()
{
System.out.println("Insert the type of the new item: [Book, article...");
typeObra = tipoInput.nextLine();
super.createnewObra();
}
....
public void addObra() {
Obras newObra = new Obras();
newObra.createnewObra();
ListObra.add(newObra);
System.out.println("> Uma nova obra foi adicionada com sucesso!\n");
....
public void BorrowObra() {
System.out.println("> Choose a book from the list: ");
showListObras();
System.out.println("\n\n> Please choose one of the items from the above list by typing it's ISBN value: ");
ISBNuser = opcaoInput.nextInt();.
if(ListObra.get(ISBN).equals(ISBNuser))
{
System.out.println("> You successfully borrowed this book");
statusBorrow = false;
}
To get an int from an ArrayList, your ArrayList would have to be defined along the lines of this:
ArrayList<Integer> arrayListOfIntegers = new ArrayList<Integer>();
or
List<Integer> listOfIntegers = new ArrayList<Integer>();
Your list appears to contain objects of class Obras.
Also, when you call ListObra.get(ISBN), this method is designed to return the object at the specified index within the list - I suspect ISBN is not an index in the list, rather an ISBN of a book?
On a separate note, try to stick to Java naming standards - variables start with lower case letters and methods use camel case (e.g. createNewObra()). It makes things easier for other developers to understand.
ListObra.get(ISBN).equals(ISBNuser)
to:
Obras o = ListObra.get(ISBN);
if (o != null && o.getISBNuser() == ISBNuser) {
System.out.println("> You successfully borrowed this book");
statusBorrow = false;
}
because you only get a object Obras and you doesn't Override equal function in Obras, so you need to get Integer ISBUser and equal to the user input.
Another Way:
Override equal:
public class Obras extends Books implements ILibrary {
#Override
public boolean equals(Object e) {
Integer i = (Integer)e;
if (this.ISBUser == i) return true;
return false;
}
}
so now can use equals function to compare:
ListObra.get(ISBN).equals(ISBNuser)

Java Pass object to method

I have a program that allows the user to choose between a binary search tree a splay tree and a red black tree. I wrote the class for the binary search tree and now im working on the splay tree but ive realized that my method that interacts with the user only works with the binary search tree. I set it up so that it will create an instance of whichever tree the user selects but down in my code I use only the variable that would be created if the user selected a binary search tree. My question is how can i make it so that I will only create an instance of the tree that the user selected and how can i use only one variable so that when i insert items or work on the tree i dont have to add more conditional statements for different trees?
this is what i have now
import java.util.Scanner;
import java.lang.Math.*;
public class Driver1
{
public static void main(String[] args)
{
//local variables
String treeChoice = null;
String choice = null;
String choice2 = null;
String command = null;
int insertAmount = -1;
String pattern;
int height = -1;
int i = -1;
//BST<Integer> myTree = null;
//ST<Integer> mySTTree = null;
int num = 0;
//Scanners to take user input
Scanner input = new Scanner(System.in);
Scanner inputt = new Scanner(System.in);
System.out.println("Which tree would you like to test (BST, ST, RBT)? ");
treeChoice = input.nextLine();
//Based on user input either a BST, Splay Tree, or RBT will be initialized.
if("BST".equalsIgnoreCase(treeChoice))
{
BST<Integer> myTree = new BST<Integer>();
}
else if("ST".equalsIgnoreCase(treeChoice))
{
//System.out.println("Splay Tree not ready yet");
ST<Integer> mySTTree = new ST<Integer>();
}
else if("RBT".equalsIgnoreCase(treeChoice))
{
System.out.println("RBT not ready yet");
//RBT<Integer> myTree = new RBT<Integer>();
}
else
{
System.out.println("Invalid Entry");
}
//Ask user how many items to input
System.out.println("How many items would you like to insert? ");
insertAmount = input.nextInt();
//ask user if the items will be random or sorted
System.out.println("Pattern (random or sorted): ");
choice2 = inputt.nextLine();
//If random, create random numbers
if("random".equalsIgnoreCase(choice2))
{
for(i = 1; i <= insertAmount; i++)
{
myTree.insert((int)(Math.random()*1000000)+i);
}
}
//else fill the tree with numbers in order from 1 to the user limit
else if("sorted".equalsIgnoreCase(choice2))
{
for(i = 1; i <= insertAmount; i++)
{
myTree.insert(i);
}
}
//Keep asking users input on what to do to the tree until user says quit
while(command != "quit")
{
System.out.println(
"Next command (insert X, delete X, find X, height, quit)?");
command = inputt.nextLine();
if (command.startsWith("insert"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.insert(num);
if(result == false)
{
System.out.println("Item already present.");
}
}
else if(command.startsWith("delete"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.delete(num);
}
else if(command.startsWith("find"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.find(num);
if(result == true)
{
System.out.println("Item present.");
}
else
{
System.out.println("Item not present.");
}
}
else if(command.startsWith("height"))
{
System.out.println("Current height of tree " + myTree.height());
}
else if(command.startsWith("quit"))
{
break;
}
System.out.println();
}
}//Close main method
as you can see I fill only myTree which would be the tree created if the user selected bst. and in the while loop i only work on myTree.
How can i make this more generic or my other idea was to take the users input and then create the instance of that tree and then pass the instance into a seperate method so that i could still use only myTree since it would refer to the instance that was passed into that method but im not sure how to pass an instance into another method. This way seems like the best but im not sure
any help is appreciated
Your trees should extend a common base class, or better, a implement common interface, say Tree, that specifies the methods to be used on all trees (find, insert, delete). Then you should have only one variable Tree myTree to which you assign an actual instance of the type the user selects.
Are you sure your above code works, however? If you do this
if("BST".equalsIgnoreCase(treeChoice))
{
BST<Integer> myTree = new BST<Integer>();
}
then the variable myTree will be unavailable after the } because the code block in which it is declared ends there. You can declare a variable at one point and assign a value to it later, like so:
Tree<Integer> myTree;
if("BST".equalsIgnoreCase(treeChoice)) {
myTree = new BinarySearchTree<Integer>();
} else if("ST".equalsIgnoreCase(treeChoice)) {
myTree = new SplayTree<Integer>();
} else if("RBT".equalsIgnoreCase(treeChoice)) {
myTree = new RedBlackTree<Integer>();
} else {
throw new IllegalArgumentException(treeChoice + " is not a valid input");
}
I very much recommend that you give your classes real names that make obvious what they represent, not just two or three letter combinations. Note that if you do not throw an exception in the last else branch, the compiler will later complain that "the variable myTree may not have been initialized".
Alternatively, you could put all your code after the tree creation if-else-statements into a method, say <T> void testTree(Tree<T> myTree) and call this method directly where you evaluate the user input, e.g. if("BST".equalsIgnoreCase(treeChoice)) testTree(new BinarySearchTree<Integer>());, but at some you will want to assign it to a variable anyway.

Shortest path using Dijkstra's algorithm

I'm currently reviving an old homework assignment, where I'm writing a program that among other functions, involves finding the shortest path in a graph using Dijkstra's algorithm.
I think I've got it right for the most part, but I keep getting NullPointerException at line 58 when executing if(currentNode.getAktuell()).
I've been trying several solutions back and forth but can't seem to figure out what is wrong but prioQueue.poll(); returns null when the queue is empty. I've tried to handle that last currentNode that eventually turns into null but have not been able to find a working solution, so I'm starting to think that I've missed out on something here.
I would really appreciate it if someone familiar with dijkstras algorithm could help me out here. There's probably a better solution to the algorithm but I only want help with finding out what is wrong with the one I've written, and not "the answer" using someone else's algorithm.
public static List<String> shortestPath(Graph<String> graph, String från, String till){
//if(!pathExists(graph, från, till))
//return null;
PriorityQueue<DjikstraObjekt<String>> prioQueue = new PriorityQueue<DjikstraObjekt<String>>();
LinkedHashMap<String, DjikstraObjekt<String>> samling = new LinkedHashMap<String, DjikstraObjekt<String>>();
for(String bla : graph.getNodes())
samling.put(bla, new DjikstraObjekt<String>(bla, Integer.MAX_VALUE, null, false));
samling.get(från).updateVikt(0);
prioQueue.add(samling.get(från));
while(!samling.get(till).getAktuell())
{
DjikstraObjekt<String> currentNode = prioQueue.poll();
if(currentNode==null)
break;
if(currentNode.getAktuell())
continue;
currentNode.aktuellNod();
for(ListEdge<String> edge : graph.getEdgesFrom(currentNode.getNode()))
{
System.out.println("get edges from");
int nyVikt = edge.getVikt() + currentNode.getVikt();
DjikstraObjekt<String> toNode = samling.get(edge.getDest());
if(!toNode.getAktuell() && nyVikt < toNode.getVikt()) {
toNode.updateVikt(nyVikt);
toNode.setFrån(currentNode.getNode());
prioQueue.add(toNode);
}
}
}
List<String> djikstaList = new ArrayList<String>();
for(int i=0;i<samling.size();i++){
if(samling.get(i).getNode()!=från){
System.out.println(samling.get(i).getNode());
djikstaList.add(samling.get(i).getNode());
}
}
return djikstaList;
}
public class DjikstraObjekt<E> implements Comparable<DjikstraObjekt<E>> {
private E nod;
private int vikt;
private E frånNod;
private boolean aktuellNod=false;
public DjikstraObjekt(E nod, int vikt, E frånNod, boolean aktuellNod){
this.nod=nod;
this.vikt=vikt;
this.frånNod=frånNod;
this.aktuellNod=aktuellNod;
}
public E getNode() {
return nod;
}
public void updateVikt(int nyvikt){
vikt=nyvikt;
}
public int getVikt() {
return vikt;
}
public boolean getAktuell() {
return aktuellNod;
}
public void aktuellNod(){
aktuellNod=true;
}
public void setFrån(E från)
{
frånNod = från;
}
public int compareTo(DjikstraObjekt<E> other) {
return getVikt() - other.getVikt();
}
}
Heres my listEdge class:
public class ListEdge<E> {
private E dest;
private String namn;
private Integer vikt;
public ListEdge(E dest, String namn, Integer vikt){
this.dest=dest;
this.namn=namn;
this.vikt=vikt;
}
public E getDest(){
return dest;
}
public void ändraVikt(Integer nyVikt){
if(vikt<0)
throw new IllegalArgumentException();
vikt=nyVikt;
}
public String getNamn(){
return namn;
}
public int compareTo(ListEdge other) {
return this.vikt.compareTo(other.getVikt());
}
public int getVikt(){
return vikt;
}
public String toString(){
return "till " + dest + " med " + namn +" "+ vikt;
}
}
These should be the relevent methods from my ListGraph class:
public List<E> getNodes(){
List<E> temp = new ArrayList<E>();
for(E test : noder.keySet()){
temp.add(test);
}
return temp;
}
public List<ListEdge<E>> getEdgesFrom(E nod) {
List<ListEdge<E>> temp = new ArrayList<ListEdge<E>>();
if(noder.containsKey(nod)){
try{
for(Map.Entry<E, List<ListEdge<E>>> test : noder.entrySet()){
if(test.getKey().equals(nod)){
System.out.println(nod+" "+test.getKey());
for(ListEdge<E> e: test.getValue()){
temp.add(e);
}
}
}
}
catch(NoSuchElementException E){
}
}
return temp;
}
I couldn't reconstruct the NullPointerException you told us about. As Leandro pointed out, the problem might lay with your implementation of ListEdge and Graph.
I did an implementation of both classes myself to test your code.
The only problem I could find was in the end where you create the result list:
for(int i=0;i<samling.size();i++){
if(samling.get(i).getNode()!=från){
This will always Result in a NullPointerException because get() expects a key and in your case that's a String, not an int. To iterate over the Map use something like
List<String> djikstaList = new ArrayList<String>();
for(String key : samling.keySet()){
if(samling.get(key).getNode()!=från){
System.out.println(samling.get(key).getNode());
djikstaList.add(samling.get(key).getNode());
}
}
Furthermore, i assume you wan't to return the actual path from from to to so you would need to add a getter getFrån() to DijkstraObjekt and then build up the list like this:
String fromNode = samling.get(to).getNode();
djikstaList.add(to);
while(fromNode != from){
fromNode = samling.get(fromNode).getFrån();
djikstaList.add(fromNode);
}
After this the List will contain the complete path (including Start and End node) in reverse order.
If wanted, I can post all of my classes I used for testing/debugging.
Cheers
tannerli
I think this might be a problem:
//...
samling.put(bla, new DjikstraObjekt<String>(bla, Integer.MAX_VALUE, null, false));
samling.get(från).updateVikt(0);
EDIT:
Sorry I thought the {} is there. Everything is ok there. I will keep looking.
Maybe try this:
if(currentNode==null || currentNode.getAktuell() == null)
break;
if(currentNode.getAktuell())
continue;

Categories