I have a class called LinkStrand which functions very similarly to a Linked List. It has toString(), size(), append(), next(), and value(), but NOT a previous() method. I am trying to write code that reverses the order of the nodes, as well as the string within each node. In order to make it easier on myself in a few of the other methods I’ve had to write, I got rid of the next node requirement in constructing a node. Here’s what the Node class looks like:
private class Node {
public Node myNext;
public String myData;
Node(String value) {
myData = value;
//myNext = next;
}
}
My .reverse() method currently reverses all of the strings within the nodes individually, but does not reverse the order of the nodes themselves. It is copied below:
public IDnaStrand reverse() {
if (this == null)
return this;
Node prevStrand = null;
Node thisStrand = myHead;
String revString;
LinkStrand val = new LinkStrand();
while (thisStrand != null){
Node hold = thisStrand.myNext;
if (revSave.containsKey(thisStrand.myData)){
revString = revSave.get(thisStrand.myData);
val.append(revString);
//System.out.println("Val is: " + val);
}
else{
revString = reverseStr(thisStrand.myData);
val.append(revString);
//System.out.println("Val is: " + val);
revSave.put(thisStrand.myData, revString);
}
thisStrand.myData = revString;
thisStrand.myNext = prevStrand;
prevStrand = thisStrand;
thisStrand = hold;
}
return val;
}
I’ve been trying to come up with some kind of way to reverse the node order, but I’m drawing a blank. Does anyone have any idea how I might go about it?
Thanks!
If you are allowed to modify
IDnaStrandandLinkStrand, add a methodprepend(Node n). Then, as you iterate through the list, just prepend each node.If you can’t modify your classes, save the
Nodes to an array in reverse order (nodeArray[size-1],nodeArray[size-2], …) then create a newLinkStrandgoing through the array in order. Alternatively you could load the array in order, then create theLinkStrandin reverse order.example:
Now you have the array, just load it into a new list! Of course adding a prepend method would be better, just have the class do