How can I convert this code to a loop? I have top defined as an instance variable of type NodeString
NodeString temp1 = top.getNext().getNext().getNext().getNext().getNext();
NodeString temp2 = top.getNext().getNext().getNext().getNext();
NodeString temp3 = top.getNext().getNext().getNext();
NodeString temp4 = top.getNext().getNext();
NodeString temp5 = top.getNext();
NodeString temp6 = top;
result.add(temp1.getData());
result.add(temp2.getData());
result.add(temp3.getData());
result.add(temp4.getData());
result.add(temp5.getData());
result.add(temp6.getData());
asked Apr 9, 2019 at 2:11
user11064680user11064680
3 Answers 3
You could build an array and then iterate it backwards. Something like,
NodeString[] arr = { top, arr[0].getNext(), arr[1].getNext(),
arr[3].getNext(), arr[4].getNext(), arr[5].getNext() };
for (int i = arr.length - 1; i >= 0; i--) {
result.add(arr[i].getData());
}
answered Apr 9, 2019 at 2:17
-
i have the array i want to clone in the main functionuser11064680– user1106468004/09/2019 02:20:15Commented Apr 9, 2019 at 2:20
-
@scott The code I have posted here is equivalent to the code in your question.Elliott Frisch– Elliott Frisch04/09/2019 02:22:02Commented Apr 9, 2019 at 2:22
-
@ElliottFrisch Is the iteration order necessary?Scary Wombat– Scary Wombat04/09/2019 02:22:26Commented Apr 9, 2019 at 2:22
-
@ScaryWombat No, but you'd need to build the array in reverse (assuming it's relevant to op's original code).Elliott Frisch– Elliott Frisch04/09/2019 02:23:50Commented Apr 9, 2019 at 2:23
-
the code posted in the comment by @shmosel worked okay for me, with some modifications. I didn't want to pass an array as a parameter.user11064680– user1106468004/09/2019 02:28:27Commented Apr 9, 2019 at 2:28
Solution using recursion.
List func(NodeString top,List result){
if(top==null){
return result;
}else{
result = func(top.next,result);
result.add(top.data);
}
return result;
}
further you can func call like this:
List result = func(top, new ArrayList());
answered Apr 9, 2019 at 4:02
You can use the following method to get the nodes list. You need to send the top node to the method and it will return the nodes list. This method is written to make sure the exact logic you have mentioned, which is to add the top node to the bottom and the child nodes to the top.
private List<NodeString> generateNodeList(NodeString topNode) {
List<NodeString> result = new LinkedList<>();
NodeString currentNode = topNode;
while(currentNode != null) {
result.add(0, currentNode);
currentNode = currentNode.getData();
}
return result;
}
answered Apr 9, 2019 at 4:41
lang-java
NodeString next = top; do result.add(0, next.getData()); while ((next = next.getNext()) != null);