简体   繁体   中英

How can i convert this piece of code to a loop?

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());

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());
}

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());

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM