简体   繁体   English

我如何将这段代码转换为循环?

[英]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 我已将top定义为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: 进一步,您可以像这样进行func调用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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