Hello all,
I would like to first state that it this is a question for a homework assignment, so I'm not looking for exact code but rather just help on something that is frustrating me. We have to create our own ADTs for this assignment and not use built in classes. So here is what I've got so far:
for the Edge class (basically like a Node class):
class Edge {
int vertex1;
int vertex2;
float weight;
Edge next;
public Edge(int v1,int v2,float w,Edge n) {
this.vertex1 = v1;
this.vertex2 = v2;
this.weight = w;
this.next = n;
}
public Edge getNext() { return this.next; }
public void setNext(Edge n) { this.next = n; }
}
for my Linked list class:
class LinkedList {
private Edge head;
private Edge tail;
public LinkedList() {
head = null;
tail = null;
}
public void Insert(Edge e) {
if (isEmpty() ) {
head = tail = e;
}
else {
tail = tail.next = e;
}
}
private boolean isEmpty() {
return head == null;
}
public void print(){
if (isEmpty()) {
System.out.println("Empty");
return;
}
Edge curr = head;
while(curr != null) {
System.out.print(curr.vertex1 + " " + curr.vertex2 + "\n");
curr = curr.next;
}
System.out.println();
}
public int size(){
int size = 0;
if(isEmpty())
return size;
Edge curr=head;
while(curr != null){
curr = curr.next;
size++;
}
return size;
}
public Edge returnHead() { return head;}
public void setHead(Edge head) { this.head = head;}
}
The implementation of the classes:
public static void createAdjacency(File f) {
int v1=0;
int v2=0;
float w=0;
for(int i = 0; i < adjacencylist.length; i++) {
adjacencylist[i] = new LinkedList();
}
try{
Scanner s = new Scanner(f);
while(s.hasNext()) {
try {
v1 = Integer.parseInt(s.next());
if(v1 == -1) {
break;
}
} catch (NumberFormatException e) {
System.out.println("Error: " + e);
}
try {
v2 = Integer.parseInt(s.next());
} catch (NumberFormatException e) {
System.out.println("Error: " + e);
}
try {
w = Float.parseFloat(s.next());
} catch (NumberFormatException e) {
System.out.println("Error: " + e);
}
Edge e = new Edge(v1, v2, w, null);
adjacencylist[v1].Insert(e);
adjacencylist[v2].Insert(e);
}
} catch (FileNotFoundException e) {
System.out.printf("%s not found\n/", f.getName());
}
}
You'll notice that I have to do a for loop to instantiate each array item as a new linkedlist, which I thought was weird. Otherwise it won't let me do adjacencylist[v1].Insert(e). My problem is that it is getting everything jumbled and I don't think it is treating adjacencylist[0] linked list as a wholey separate list than adjacencylist[1] and so forth. Any ideas with this would be greatly appreciated! Any tips or pointers in general (I'm new to Java) would also be welcome as my main goal is to be a better programmer in general.
Thank you!